Reputation: 45
So I'm trying to write this line to a text file;
sprintf(line, "%d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %d, %s\n",
gen_no, total_time,
progp->total_fitness,
progp->entopy_breakdown[0],
progp->entopy_breakdown[1],
progp->entopy_breakdown[2],
progp->entopy_breakdown[3],
progp->entopy_breakdown[4],
progp->entopy_breakdown[5],
progp->entopy_breakdown[6],
0,
tree_as_char);
fprintf(fp, line);
fclose(fp);
Everything in the line is written correctly apart from when tree_as_char has "%" i.e. "%25" symbols in it (sometimes it writes one and then the proceeding char is escaped, sometimes it does't write any). All the other symbols in tree_as_char are written to the file correctly, and printing the line prints the % symbols correctly. Maybe I'm not escaping it properly somewhere?
Thanks!
Phil
Upvotes: 0
Views: 454
Reputation: 76413
Oh dear, just noticed you're writing sprintf
, and then call fprintf
. Now that's just not necessary. You can easily save on that sprintf
call by writing:
fprintf(fp, "%d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %d, %s\n",
gen_no, total_time,
progp->total_fitness,
progp->entopy_breakdown[0],
progp->entopy_breakdown[1],
progp->entopy_breakdown[2],
progp->entopy_breakdown[3],
progp->entopy_breakdown[4],
progp->entopy_breakdown[5],
progp->entopy_breakdown[6],
0,
tree_as_char);
That ought to work, and you won't have any more issues with the percent signs in the tree_as_char
string. If you still need that line
var for other things, you can choose: parse the line, adding secondary %
chars before writing to the file pointer, use fwrite
, or, better (perhaps): use fputs
:
sprintf(line, "%d, %f, %f, %f, %f, %f, %f, %f, %f, %f, %d, %s\n",
gen_no, total_time,
progp->total_fitness,
progp->entopy_breakdown[0],
progp->entopy_breakdown[1],
progp->entopy_breakdown[2],
progp->entopy_breakdown[3],
progp->entopy_breakdown[4],
progp->entopy_breakdown[5],
progp->entopy_breakdown[6],
0,
tree_as_char);
fputs(fp, line);
If you want to print a percent sign (%
) using any of the *printf
functions, you have to escape the percent sign itself. Just write %%
to get one %:
printf("%d%%", 10);
will print 10%
If your tree_as_char
contains percent signs, fprintf
will just consider that as a placeholder, so you'll have to parse that string first, and add a second percent sign if needed.
Upvotes: 3
Reputation: 1614
fprintf
will treat any %
symbol in second parameter as a formatter. Try fprintf(fp, "%s", line);
.
Upvotes: 4