读取某行文件方法

今天又突发奇想,想打印一个字符画出来,纯手工把70多行字符定义成了字符串。
结果这玩意儿里有一堆字符编译器不认,要是调整渐变字符重新弄就又要花半天,实在受不了那气,决定弄一个能自动读取txt中字符保存到字符串的程序。


代码如下

								//选择要读取哪一行,传递文件路径
string GetCertainRowFile(const int CertainLine,const string FilePath)
{
    const char *temp = FilePath.c_str();
    FILE *fp = fopen(temp,"r");
    if(fp==NULL)
    {
        const string ErrorReport = "You opened up the emptiness";
        cout<<ErrorReport<<endl;//报错
        return ErrorReport;
    }
    int currentLine = 1;//当前读取的行
    const int MAX = 1024;
    while(!feof(fp))
    {
        char str[MAX];
        fgets(str,MAX,fp);
        if(CertainLine==currentLine)
        {
            return str;
        }
        currentLine++;
    }
    fclose(fp);//关闭文件
}

猜你喜欢

转载自blog.csdn.net/jgjfror/article/details/113813109