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

Kar*_*ber 5 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;
Run Code Online (Sandbox Code Playgroud)

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

Lei*_*igh 5

为了使其正常工作,有一些变化.

更改int lensize_t len正确的类型.

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

while ((read = getline(&line, &len, file)) != -1) {
Run Code Online (Sandbox Code Playgroud)

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

printf("Retrieved line of length %d:\n", read);
Run Code Online (Sandbox Code Playgroud)