C: use fwrite to write char to different line

25,594

Solution 1

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

Solution 2

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

Share:
25,594
Jake
Author by

Jake

# SOreadytohelp

Updated on July 16, 2022

Comments

  • Jake
    Jake almost 2 years

    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.