Socrates
Socrates

Reputation: 405

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?

Upvotes: 1

Views: 549

Answers (2)

Jeffrey
Jeffrey

Reputation: 11430

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){

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

The else branch will be executed when i==0 because i==1 is false then.

You may want to add one more else.

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

Upvotes: 4

Related Questions