Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用c语言打印文件的某一行_C_File_Printing - Fatal编程技术网

用c语言打印文件的某一行

用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

我试图用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;

}

只需添加一个
printf(“%s”,行)。我试过了,但它一直说行是未定义的:(你必须在while循环中打印它。或者当我在代码中向上移动它时,它会打印整个文本文件,我只想打印第8行。我将它放在while循环中(在else语句之后,但在大括号之前),但它仍然打印整个文本,我只想要第8行