我正在尝试用c打印文件的某一行。到目前为止,我认为我已成功读取文本文件的第 8 行,但我的问题是如何使用此代码打印该行?
谢谢!!
这是到目前为止的代码:
int lineNumber = 8;
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)
{
//use line or in a function return it
//in case of a return first close the file with "fclose(file);"
}
else
{
count++;
}
}
fclose(file);
}
这工作得很好。
您是否缺少主函数,或者它只是您发布的代码片段?
int lineNumber = 8;
static const char filename[] = "Text.txt";
int main()
{
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)
{
//use line or in a function return it
// //in case of a return first close the file with "fclose(file);"
printf("n str %s ", line);
fclose(file);
return 0;
}
else
{
count++;
}
}
fclose(file);
}
return 0;
}