c - 如何从C中的文件中读取一行

标签 c file getline

<分区>

我想逐行读取文件中的行,但它对我不起作用。

这是我尝试做的:

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;

有什么建议为什么不起作用吗?

最佳答案

为了使其正常工作,需要进行一些更改。

int len 更改为 size_t len 以获得正确的类型。

getline() 语法不正确。应该是:

while ((read = getline(&line, &len, file)) != -1) {

printf 行也应该修改,打印返回的数字而不是 char 和字符串解释:

printf("Retrieved line of length %d:\n", read);

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

相关文章:

image - 如何在 C++ 中使用 GDI+ 获取图像文件类型?

python - 有没有办法读取 .txt 文件并将每一行存储到内存中?

c++ - 是否可以在没有用户输入的情况下跳过 getline()?

c++ - 如何对未知数据量使用 getline()?

python - 可以在循环内多次使用 getline() 吗? - Cython,文件读取

c - 释放四叉树项目中的内存

objective-c - xcode 中的 strcpy

android - 我想在 Android 项目中读取文件

c - 将 char 数组传递给另一个函数

c - 在c中的文件末尾添加信息