Hang Chen
Hang Chen

Reputation: 863

Read a text file line by line and retrieve the content of each line in C

Say a text file would be like:

1, 2345, 7788, 463, ABC
2, 387, 1100, 321, CCC
2, 2222, 22222, 22, DSA

So there are 3 lines in this text file, and my project needs us to realize a function that read this text file line by line, and retrieve each line's content when a specific line is read, and then examine the content of this line.

For example, I would begin to read this file from the first line. So when this first line is read(1, 2345, 7788, 463, ABC), I will first need to store this line into a string (say it's char[] str), and then I need to break this str into 5 pieces, and each piece contain those five different filed-content separated by the comma, say p1, p2, p3, p4 and p5. Then I need to examine if the p3 is "1100". If it is, then close this file and continue the program, and if it's not, then I would need to continue to read the second line and do the same thing, and apparently 1100 is the third filed of the second line, so after reading this line the function would terminate.

Now could anybody tell me how could I implement it? I'm very new to C and I've searched the internet and got something about fgets(), like:

if (fgets(str, 60, "text.txt")!=NULL){
    puts(str);
}

but here I can't see any hint that this frets() reads the text file line by line.

Thanks in advance! :D

Upvotes: 1

Views: 643

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>

int main(){
    char str[64];
    int p1, p2, p3, p4;
    char p5[16];
    FILE *fp;
    int i;
    fp=fopen("text.txt", "r");
    while(fgets(str, sizeof(str), fp)!=NULL){
        if(sscanf(str, "%d, %d, %d, %d, %15s", &p1, &p2, &p3, &p4, p5)==5){
            if(p3 == 1100)
                break;
            //do something
            puts(str);
        }
    }
    fclose(fp);

    return 0;
}

Upvotes: 0

ryyker
ryyker

Reputation: 23218

How to use your code to examine each line?

using code from @Mike, add the following:

char str[60];
FILE* f = fopen("text.txt", "r");
if (f == NULL) exit(1);
while(fgets(str, 60, f) != NULL){
    if(strstr(str, "1100")  //Add these lines to test for "1100"
    {
          puts("Found 1100!", stdout);//optional
          puts(str, stdout);//optional
          fclose(f);
          return;
    } 
    fputs(str, stdout);
}
fclose(f);

Upvotes: 0

Mike Dunlavey
Mike Dunlavey

Reputation: 40669

You want this:

char str[60];
FILE* f = fopen("text.txt", "r");
if (f == NULL) exit(1);
while(fgets(str, 60, f) != NULL){
    fputs(str, stdout);
}
fclose(f);

Upvotes: 1

Related Questions