0

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:

  1. This is the first trial line in the file.
  2. 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:

  1. This is the first trial line in the file.
  2. 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?

JWX123
  • 63
  • 4
  • 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. – JWX123 Feb 20 '18 at 10:42
  • So your code scans DIFFERENT text files creates with different tools (vi, Code::Blocks). I recommend to take a common dump utility and look at the actual content. You can also use a diff utility for that task. Usually the line endings may differ. It looks like `vi` adds a new line at the end, since you've entered complete lines. `Code::Blocks` has a text editor with more freedom, including the freedom to omit the last new line. – harper Feb 20 '18 at 13:47
  • @user3386109 The question wasn't about the code in the example but about the data that is evaluated with the code. Please reopen. – harper Feb 20 '18 at 13:49
  • If that's the case, then the second set of code, which is still obviously wrong, should be completely removed. – user3386109 Feb 20 '18 at 20:24
  • And if the real question is, "Why does vi put an extra newline at the end of my file?", then you should just ask that question. Which means that you should remove all of the code, and remove the C tag. – user3386109 Feb 20 '18 at 20:45

0 Answers0