Jake
Jake

Reputation: 16837

C: use fwrite to write char to different line

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.

Upvotes: 4

Views: 31001

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 133975

What "extra characters" do you see? You do realize that the "a+" parameter to fopen opens the file for appending, so that you're writing to the end of the file. Did you perhaps mean "w+", which will overwrite the file?

You could use:

fputc((int)ch, fp);
fputc((int)'\n', fp);

Or even fprintf(fp, "%c\n", ch);

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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).

Upvotes: 10

Related Questions