我正在尝试在 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;
}
关于c - 在c中打印文件的某一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800777/