Search code examples
linuxmatrixprintfcelloctave

In octave, printf gives strange error


In GNU Octave, I'm getting an error with this code.

A = cell(10,1);
A{5,1} = "foobar";
outputFile = fopen("mytext.txt", "w");
printf(outputFile, "%s", A{5,1});

I get this error:

error: printf: format TEMPLATE must be a string

This error message is not Helpful, The google does not know what this error is! what is wrong?


Solution

  • Found the solution to this error.

    The very first parameter you are passing into printf MUST be a valid format string. You are passing it a file handle. If you want to pass a file handle, you should be using fprintf instead. If you specify a first parameter as a file, printf gives you the above error.

    You should be doing this instead:

    A = cell(10,1);
    A{5,1} = "foobar";
    outputFile = fopen("mytext.txt", "w");
    fprintf(outputFile, "%s", A{5,1});        
    

    Or, if you wanted to print to the screen, remove the outputFile parameter:

    A = cell(10,1);
    A{5,1} = "foobar";
    outputFile = fopen("mytext.txt", "w");
    printf("%s", A{5,1});
    % Here printf successfully casts the cell as a string.  no error.
    

    You are passing bad parameters to printf and Octave tries to make sense of nonsense. Review this webpage to see what can and cannot be passed into octave's printf:

    http://www.gnu.org/software/octave/doc/interpreter/Formatted-Output.html#doc-printf