Search code examples
cfilefgets

Loop doesn't work in C programming


I want to code a program that scans each line and print it. Also this process should keep on when the specific line was detected. Here is my file content :

1
2
3
4
5
6
7
8
9

and the code :

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *file;
int main(){
    file=fopen("numbers.txt","r");
    char line[10];

while(1){
         fgets(line,10,file);
         printf("%s \n\n",line);
         if(strcmp(line,"6")) break;
}

    fclose(file);
    system("pause");
    return 0;
}

But loop doesn't work and print only first line. Where is the problem?


Solution

  • This should work:

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    FILE *file;
    int main(){
        file=fopen("numbers.txt","r");
        char line[10];
    
        while(1){
                 fgets(line,10,file);
                 printf("%s \n\n",line);
                 if(!strcmp(line,"6\n")) break;
        }
    
        fclose(file);
        system("pause");
        return 0;
    }
    

    You had two problems, first strcmp returns 0 if strings are equal, second fgets returns new line mark '\n', so you have to match it too.