在c中打印文件的某一行

时间:2014-04-02 03:07:15

标签: 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 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);
}

1 个答案:

答案 0 :(得分:1)

这完全没问题。

您是否遗漏了主要功能,或者只是您发布的代码段?

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;

}