用c语言打印文件的某一行
我试图用c语言打印文件的某一行。到目前为止,我认为我已经成功地阅读了文本文件的第8行,但我的问题是如何使用此代码打印该行 谢谢 这是迄今为止的代码:用c语言打印文件的某一行,c,file,printing,C,File,Printing,我试图用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 suit
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;
}
只需添加一个
printf(“%s”,行)代码>。我试过了,但它一直说行是未定义的:(你必须在while循环中打印它。或者当我在代码中向上移动它时,它会打印整个文本文件,我只想打印第8行。我将它放在while循环中(在else语句之后,但在大括号之前),但它仍然打印整个文本,我只想要第8行