我的程序從文件中正確讀取了特定行,但它從我指定的行中讀取整個文件。我試圖一次僅打印一行。我怎麼才能讓它只讀一行?從c代碼中的文件中讀取一行代碼
代碼:
int main()
{
int lineNumber = 5;
static const char filename[] = "Text.txt";
FILE *file = fopen(filename, "r");
int count = 0;
if (file != NULL)
{
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count == lineNumber)
{
printf("%s", line);
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
}
查看鏈接http://rosettacode.org/wiki/Read_a_file_line_by_line –