Conservative. Idaho. Software engineer. Historian. Trying to prevent Idiocracy from becoming a documentary.
Email complaints/requests about copyright infringement to clayton @ claytoncramer.com. Reminder: the last copyright troll that bothered me went bankrupt.
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.
Subscribe to:
Post Comments (Atom)
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.)
ReplyDeleteMemory + glibc man page on Ubuntu Trusty + Harbison and Steele all say %% is supposed to do the trick.
ReplyDeleteOdd.
ReplyDelete#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.
Rick: I think you have it; need to fflush.
ReplyDeleteThat is odd.
ReplyDeleteInside 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
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