#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *input_f;
input_f = fopen("Input.txt", "r"); //Opens the file in read mode.
if (input_f != NULL)
{
char line[2048];
while( fgets(line, sizeof line, input_f) != NULL )
{
//do something
}
fclose(input_f); //Close the input file.
}
else
{
perror("File couldn't opened"); //Will print that file couldn't opened and why.
}
return 0;
}
你好。我知道在C语言中可以使用以下代码逐行读取,但我不想限制行大小,比如像这个代码一样限制为2048。
char line[2048];
while (fgets(line, sizeof(line), file)) {
// do something with line
}
我考虑使用malloc,但是在读取行之前我不知道行的大小,所以我认为这是不可能做到的。
有没有办法不限制行大小呢?
这个问题只是出于我的好奇心,请谢谢。
getchar()
+realloc()
,还有getline()
。 - undefined