阅读特定行数

huangapple go评论58阅读模式
英文:

Reading specific number of lines

问题

要在C中读取特定行数的内容应该如何做?有什么提示,因为我似乎找不到相关的线程。

我想要从文件中读取N行,N是由用户提供的参数。

直到这一点,我一直是这样读取文件的:(逐行直到NULL)

int main(void) {
    char line[50];
    FILE *file;
    file = fopen("filename.txt", "r");
    printf("文件包含:\n");

    while (fgets(line, 50, file) != NULL) {
        printf("%s", line);
    }
    fclose(file);
    return(0);
}
英文:

How should I read a specific number of lines in C? Any tips, since I can't seem to find a relevant thread.

I would like to read N lines from a file and N would be argument given by the user.

Up until this point I have been reading files this way: (line by line until NULL)

int main(void) {
    char line[50];
    FILE *file;
    file= fopen("filename.txt", "r"); 
    printf("File includes:\n");

    while (fgets(line, 50, file) != NULL) {
        printf("%s", line);
    }
    fclose(file);
    return(0);
}

答案1

得分: 3

如果用户提供了N,您可以使循环计数达到N

for (int i = 0; i < N && fgets(line, sizeof line, file); ++i) {
    fputs(line, stdout);
}
英文:

If N is given by the user, you could just make your loop count up to N:

for (int i = 0; i &lt; N &amp;&amp; fgets(line, sizeof line, file); ++i) {
    fputs(line, stdout);
}

huangapple
  • 本文由 发表于 2023年2月6日 14:10:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定