c - 在c中打印文件的某一行

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

最佳答案

这工作得很好。

您是否缺少主要功能,或者只是您发布的代码片段?

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/

相关文章:

file - MATLAB如何在文本文件中写入文件头

java - 查找项目源文件夹中特定扩展名的所有文件

user-interface - 如何加速matlab 'print'函数

c - 递归地找到列表中的完美平方和

c - 打印列表时省略最后一个逗号

c - 三元运算符可用于以下用途吗?

c - 为什么我的朴素 sizeof 运算符需要 char* 转换?

java - 我可以像数组一样从文件中读取对象吗?

java打印 - 边框的设置大小

c# - 打印不规则线条的条码