简体   繁体   English

从 C 中的文本文件中读取前 N 行

[英]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.我正在尝试从文件中解析一些结果,并在 C 程序中读取它的前两行。 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.但问题是line_string一直指向文件的第一行,并且在 while 循环中没有进展。 What am I doing wrong?我究竟做错了什么?

The else branch will be executed when i==0 because i==1 is false then. else分支将在i==0时执行,因为此时i==1为假。

You may want to add one more else .您可能还想再添加一个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;
    }
}

With

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

You'll enter the two if s the first time round.您将在第一轮中输入两个if s。 You need an else to tell the compiler to not enter the second if , when i goes from 0 to 1:i从 0 变为 1 时,您需要一个else来告诉编译器不要输入第二个if

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM