0

I have a text file with this content:

what to write

I first created this file like this:

FILE * fPointer;
fPointer = fopen("fileName.txt" , "w"); //create the file
fprintf(fPointer,"what to write\n"); //write to the file

I read the file content like this:

fPointer = fopen("fileName.txt" , "r"); //too read the file
char singleLine [100];

while(!feof(fPointer)){ //while file is not finished
    fgets(singleLine,100,fPointer);
    puts(singleLine);
}

I expected to get the "what to write" content of the file only once but this is the result:

enter image description here

As you can see, for some reason I am getting the file content 2 times, any ideas on why this may happen?

  • I have checked that the file location is correct and that the file exists.

  • I have also checked this answer but I am not familiar with the getc method and I want to know what I am doing wrong.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • Second place in the [FAQ list](https://stackoverflow.com/questions/tagged/c?sort=frequent&pageSize=15). Is better as `while(fgets(singleLine, sizeof singleLine, fPointer) != NULL) {...}` – Weather Vane Jun 28 '19 at 19:08
  • @Weather Vane , thank you - Its really weird that I missed it. – Tamir Abutbul Jun 28 '19 at 19:09
  • 1
    It's weird. If I was teaching C, I probably wouldn't even mention `feof()` — it is something I almost never use, and which I never use to control a loop. However, the sheer number of questions relating to `while (!feof(fp))` means an awful lot of Pascal programmers must have learned to teach C (badly). – Jonathan Leffler Jun 28 '19 at 19:15
  • @Jonathan Leffler , I am taking C as a fun project to learn before I start my computer science degree later this year. Even if I am learning something that is not 100% correct I believe that its better than nothing. I am coming from Java and only after I started with C I started to appreciate it. Anyway - It was nice to hear your opinion on the subject. – Tamir Abutbul Jun 28 '19 at 19:21

0 Answers0