C语言 如何从C中的文件中读取一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19813949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a line from a file in C
提问by KaramJaber
I want to read lines from a file line-by-line, but it's not working for me.
我想逐行读取文件中的行,但它对我不起作用。
Here is what I tried to do:
这是我尝试做的:
FILE *file;
char *line = NULL;
int len = 0;
char read;
file=fopen(argv[1], "r");
if (file == NULL)
return 1;
while ((read = getline(&line, len, file)) != -1) {
printf("Retrieved line of length %s :\n", &read);
printf("%s", line);
}
if (line)
free(line);
return 0;
Any suggestions why that isn't working?
任何建议为什么这不起作用?
采纳答案by Leigh
To get it to work correctly, there's a few changes.
为了让它正常工作,有一些变化。
Change int lento size_t lenfor the correct type.
更改int len到size_t len正确的类型。
getline()syntax is incorrect. It should be:
getline()语法不正确。它应该是:
while ((read = getline(&line, &len, file)) != -1) {
And the printfline should also be modified, to print the number returned instead of a charand string interpretation:
并且printf还应修改该行,以打印返回的数字而不是char字符串解释:
printf("Retrieved line of length %d:\n", read);
回答by unwind
Your second argument to getline()is (very) wrong.
你的第二个论点getline()是(非常)错误的。
It should be size_t *, you're passing int. You should have received compiler warnings for this problem.
应该是size_t *,你通过了int。您应该已经收到有关此问题的编译器警告。
Make it:
做了:
size_t len;
and in the call:
并在通话中:
getline(&line, &len, file)
Also the return value is of type ssize_t, not char.
此外,返回值的类型是ssize_t,而不是char。
You should really read the manual page for getline()and make sure you understand it, before writing code to use the function.
在编写使用该函数的代码之前,您应该真正阅读手册页getline()并确保您理解它。
回答by user3651854
Alternatively you can also use this code. It will read the whole file line by line and print those lines.
或者,您也可以使用此代码。它将逐行读取整个文件并打印这些行。
char buf[1000];
ptr_file =fopen("input3.txt","r");
if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
printf("%s",buf);

