Edit: This has nothing to do with why while(!feof(f_ptr)) is wrong. I can use while(fscanf(... just as well. The issue is with how the two editors display the output.
I have a text file which contains the following:
This is the first trial line in the file.
and this is the second line.
The code's function is to display the content of the text file like this:
- This is the first trial line in the file.
- and this is the second line.
Here is code that uses fgetc:
#include <stdio.h>
main(){
FILE *f_ptr=fopen("C:\\Users\\ABC\\Desktop\\test.txt","r");
char ch;
int i=1;
if(f_ptr==NULL){
printf("ERROR: File could not be opened.");
exit(0);
}
else{
printf("%d. ",i);
i++;
while((ch=fgetc(f_ptr))!=EOF){
putchar(ch);
if(ch=='\n'){
printf("%d. ",i);
i++;
}
}
}
}
This code uses fgets:
#include <stdio.h>
main(){
FILE *f_ptr=fopen("C:\\Users\\ABC\\Desktop\\test.txt","r");
char line[100];
int i=1;
if(f_ptr==NULL){
printf("ERROR: File could not be opened.");
exit(0);
}
else{
while(fscanf(f_ptr,"%s",line)!=EOF){
fgets(line,sizeof(line),f_ptr);
printf("%d. %s",i,line);
i++;
}
}
}
Both of them work fine when run in Codeblocks but when I run them in Vi editor I always get an extra line:
- This is the first trial line in the file.
- and this is the second line.
3.
Does this have something to do with the way nextline characters are read by Codeblocks and Vi? How can I fix this?