Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

fgets - Reading first N lines from a text file in C

I am trying to parse some results from a file and read, let us say, the first 2 lines of it in a C program. Here is what I am doing:

int i=0;
while (fgets(line_string, line_size, fp) != NULL){
    if (i==0){
        some_variable = ((int) atoi(line_string));
        i++;
    }
    if (i==1){
        some_other_variable = ((int) atoi(line_string));
        i++;
    }
    else{
        break;
    }
}

But the problem is line_string keeps pointing to the first line of the file and doesn't progress in the while loop. What am I doing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With

if (i==0){
    some_variable = ((int) atoi(line_string));
    i++;
}
if (i==1){

You'll enter the two ifs the first time round. You need an else to tell the compiler to not enter the second if, when i goes from 0 to 1:

if (i==0){
    some_variable = ((int) atoi(line_string));
    i++;
}
else if (i==1){

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...