Thursday, December 3, 2015

Feeling More Stupid Than Usual

I need to write % into a file in C.  I tried putting %% in the format control string.  Did no\t work.  I tried %c with '%' in the data list.  Nope.  I tried fputs("%\n", fileHandle);  Nope.

6 comments:

  1. Those all sound like they should do the job. Can't be sure what's going on without a complete chunk of code, but the first thing I wonder is if you're flushing/closing the file before checking to see if your single additional byte is there. (The stdio stuff, which you're using, does lots of buffering.)

    ReplyDelete
  2. Memory + glibc man page on Ubuntu Trusty + Harbison and Steele all say %% is supposed to do the trick.

    ReplyDelete
  3. Odd.

    #include

    void main()
    {
    FILE *fp = fopen("test.txt", "w");
    fprintf(fp, "xx%%");
    fclose(fp);
    }


    worked for me--test.txt was created with 'xx%' in it.

    ReplyDelete
  4. Rick: I think you have it; need to fflush.

    ReplyDelete
  5. That is odd.

    Inside printf/sprintf/fprintf, the "%%" in the format control string should be seen by the app as a control code for a "%" character in output.

    I've never used fputs/puts, but they are supposed to allow single "%" characters in many situations.

    Here's a thought: are you constructing the string in one function call, and then later running the result through another function that will also try to interpret the "%" character?

    Something like this:
    int pct_val = 1; // assumed for example
    sprintf(array, "percent is %d%%", pct_val); // "percent is 1%" in array
    fprintf(file, array); // "percent is 1%" passed to fprintf...and the "%" char disappears in output

    ReplyDelete
  6. Actually the code was right. I had a makefile that rebuilt the binary, but didn't run the binary, so my output files weren't being recreated. Dumb.

    ReplyDelete