C: use fwrite to write char to different line

Jake picture Jake · Apr 21, 2012 · Viewed 23.1k times · Source

I have to write to a file as follows:

 A
 B
 C
 D
 ...

Each character of the alphabet needs to be written to different line in the file. I have the following program which writes characters one after another:

 FILE* fp;
 fp = fopen("file1","a+");
 int i;
 char ch= 'A';
 for(i=0; i<26; i++){
     fwrite(&ch, sizeof(char), 1, fp);
     ch++;
 }
 fclose(fp);

How should I change the above program to write each character to a new line. (I tried writing "\n" after each character, but when I view the file using VI editor or ghex tool, I see extra characters; I am looking for a way so that vi editor will show file exactly as shown above).

I tried using the following after first fwrite:

 fwrite("\n", sizeof("\n"), 1, fp);

Thanks.

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Apr 21, 2012
fwrite("\n", sizeof("\n"), 1, fp);

should be

fwrite("\n", sizeof(char), 1, fp);

Otherwise, you are writing an extra \0 that is part of zero-termination of your "\n" string constant (sizeof("\n") is two, not one).