Search code examples
cfeof

Comparing syntax to feof


Hi guys i am wirting a c programme here and i am trying to print two lines from a text file at a time the problem is that when on the last line if the lines are odd, 3 lines 5 lines. It will print the last line twice.I cant find the comparison of if function for thsi particualr question. is it a bool? I am trying ferror(file) currently

    FILE *file;

    printf("Hello!\n");
    printf("Please input file name(without.txt):\n");

    scanf("%s", input);
    strcat(input,".txt");
    file = fopen( input , "r" );

    while(!(feof(file)))
    {

        for(i=0; i<2; i++){
        **if(feof(file)==ferror(file))**
        {
            printf("File ended");
                return 0;
        }
        else
        {
            fgets(return_char, 200, file);
            printf("%s\n", return_char);
        }
    }

    }

Example of input :

i have a cat

i have a dog

i have a cow

Expected output :

first round

i have a cat

i have a dog

second round :

i have a cow

Current output : first round :

i have a cat

i have a dog

second round :

i have a cow

i have a cow


Solution

  • Try this code-

    #include<stdio.h>
    #include<string.h>
    int main()
    {
            int i;
            FILE *file;
            char input[20],return_char[50],ch;
            printf("Hello!\n");
            printf("Please input file name(without.txt):\n");
    
            scanf("%s", input);
            strcat(input,".txt");
            file = fopen( input , "r" );
            i=2;
            while(fgets(return_char, 200, file))
            {
                    if(i==0){ 
                            printf("Do you want to continue(y/n)\n");
                            scanf(" %c",&ch);
                            if(ch == 'y'){
                                    printf("%s\n", return_char); 
                                    i=1; // making i=1 to read further line.
                            }
                            else{
                                    fclose(file);
                                    return 0;
                            }
                    }
                    else{
                            printf("%s\n", return_char);
                            i--;
                    }
            }
    }
    

    In this program when i=0 the return_char will have the third line of the file. So i am making i=1 again to read next line and so on.