英文:
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 < N && fgets(line, sizeof line, file); ++i) {
    fputs(line, stdout);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论