Writing to file in c

I have an array char

b[20]

that I want to write to a file. After each iteration, the value b[20]

changes, so I would like to write a line on each line of the file on each iteration. So how can I change the newline in the file and also put in the character array?

+2


a source to share


2 answers


Sort of:



FILE *fp = fopen("file.txt","w");
// check for error
char b[20];

while(some_condition) {

 // populate the char array b and terminate it with NULL char.

 // write to file...and write a newline.
 fprintf(fp,"%s\n",b); 
}

      

+7


a source


Assuming the char array contains a null terminated string:



fprintf(file, "%.20s\n", b);

      

+3


a source







All Articles