4

Why is the below program not printing the first character of the newly created text file ("E") as expected? It's a simple program and I tried to look at the issue from all aspects but couldn't find the reason. The text file is being created on my D drive with the content "EFGHI", but for some reason "E" is not being read even if I rewind and read using getc() and the output is -1.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int x;
    FILE *fp;
    fp=fopen("F:\\demo.txt","w");
    if(fp==NULL)
        puts("Write error");
    fputs("EFGHI",fp);
    rewind(fp);

    x=getc(fp);
    printf("%d",x);
    fclose(fp);
}

UPDATED:

    #include<stdio.h>
    #include<stdlib.h>

    int main()
    {
        int x;
        FILE *fp;
        fp=fopen("F:\\demo.txt","w+");
        if(fp==NULL)
        {
            puts("Write error");
            exit(EXIT_SUCCESS);
        }
        fputs("EFGHI",fp);
        rewind(fp);

        while(!feof(fp))
        {
            x=getc(fp);
            printf("%d\n",x);
        }
        fclose(fp);
     }
Meathead
  • 493
  • 2
  • 6
  • 15
  • 2
    You have opened the file for writing only. – M Oehm Oct 28 '15 at 14:42
  • @MOehm Can you also look at the comment I have left under Almo's answer in relation to the update to my code? – Meathead Oct 28 '15 at 14:56
  • The edit seems to be a answer to the problem, rather then an update to the question. If indeed an answer, post the answer below and revert the question to a former state. If is another question, post a new question. – chux - Reinstate Monica Oct 29 '15 at 00:16

2 Answers2

8

File mode "w" opens the file for writing only.

Use "w+" to open a file for writing and reading.

(Please see man fopen for more file modes.)


Regarding getc() returning -1, verbatim from man getc:

[...] getc() [...] return[s] the character read as an unsigned char cast to an int or EOF on end of file or error.

EOF typically equals -1. To test this do a printf("EOF=%d\n", EOF);

alk
  • 69,737
  • 10
  • 105
  • 255
4

fp=fopen("F:\\demo.txt","w");

Opens the file for writing, then you try to read from it. That's not going to work.

I'll also note that your program keeps trying to use fp even if it fails to be created since your if checking fp only prints an error, it doesn't stop the program.

Almo
  • 15,538
  • 13
  • 67
  • 95
  • I updated the code and it's working fine except that it's printing an unexpected 6th number "-1". Can you explain why? Isn't the position pointer expected to encounter EOF after reading 5th character thereby causing the while loop to exit? – Meathead Oct 28 '15 at 14:55
  • My guess is that `while(!feof(fp))` checks the last character read. So when you hit EOF with `x=getc(fp);`, you print it first, then the while exits. – Almo Oct 28 '15 at 15:06
  • Please ignore my last comment. I got what's happening. – Meathead Oct 28 '15 at 15:06