gpt4 book ai didi

c - 在 C 中一次读取一行

转载 作者:太空狗 更新时间:2023-10-29 16:45:31 25 4
gpt4 key购买 nike

在C语言中,可以使用哪种方法一次读取一个文件中的一行?

我正在使用 fgets 函数,但它不起作用。它只读取空格分隔的标记。

要做什么?

最佳答案

使用以下程序从文件中逐行获取。

#include <stdio.h>
int main ( void )
{
char filename[] = "file.txt";
FILE *file = fopen ( filename, "r" );

if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); //print the file contents on stdout.
}

fclose(file);
}
else {
perror(filename); //print the error message on stderr.
}

return 0;
}

关于c - 在 C 中一次读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com