jeudi 19 février 2015

How to write text to file using \n and fprintf in C

I am fairly new to C and am struggling when it comes to the concept of string building and how it works. Essentially I am trying to output a report to a .txt document with multiple "/n" new lines. Here is my string, named s:



char buf[256];
int s = sprintf(buf, "Mean %f", a);
s += sprintf(buf+s, " \nMode %i", b);
s += sprintf(buf+s, " \nMedian %f", c);
s += sprintf(buf+s, " \nStandard Deviation %f", d);


And if I printf("%s\n", buf); to console, it works fine. However, I am trying to write it to a file with the new lines included. Currently when I do this:



FILE *file = fopen(filename, mode);
fprintf(file, input);


It does not print the new lines, just one long string. What am I doing wrong?


I have looked into it, and found the only solution is to directly print each line to the file i.e



fprintf(file, "mean is %f \n", a);
fprintf(file, "mode is %i \n", b);


and so on.... I want to avoid this. Any help?


Aucun commentaire:

Enregistrer un commentaire