C++文件读写操作(三)如何统计文本的行数及如何读取文件某一行内容

相关文章


C++文件读写操作(一)将字母表写入TXT文本文件 


C++文件读写操作(二)逐字符读取文本和逐行读取文本 


C++文件读写操作(三)如何统计文本的行数及如何读取文件某一行内容 


C++文件读写操作(四)读取文件数据到临时数组





 

//如何统计文本的行数及如何读取文件某一行内容:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int CountLines(char *filename)
{
    ifstream ReadFile;
    int n=0;
    string tmp;
    ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件
    if(ReadFile.fail())//文件打开失败:返回0
    {
        return 0;
    }
    else//文件存在
    {
        while(getline(ReadFile,tmp,'\n'))
        {
            n++;
        }
        ReadFile.close();
        return n;
    }
}

string ReadLine(char *filename,int line)
{
    int lines,i=0;
    string temp;
    fstream file;
    file.open(filename,ios::in);
    lines=CountLines(filename);

    if(line<=0)
    {
        return "Error 1: 行数错误,不能为0或负数。";
    }
    if(file.fail())
    {
        return "Error 2: 文件不存在。";
    }
    if(line>lines)
    {
        return "Error 3: 行数超出文件长度。";
    }
    while(getline(file,temp)&&i<line-1)
    {
        i++;
    }
    file.close();
    return temp;
}
int main()
{
    int line;
    char filename[]="inFile.txt";
    cout<<"该文件行数为:"<<CountLines(filename)<<endl;
    cout<<"\n请输入要读取的行数:"<<endl;
    while(cin>>line)
    {
        cout<<"第"<<line<<"行的内容是 :"<<endl;
        cout<<ReadLine(filename,line);
        cout<<"\n\n请输入要读取的行数:"<<endl;
    }
}
/**********************************
程序运行情况如下:
该文件行数为:26

请输入要读取的行数:
-3
第-3行的内容是 :
Error 1: 行数错误,不能为0或负数。

请输入要读取的行数:
4
第4行的内容是 :
 4      d

请输入要读取的行数:
8
第8行的内容是 :
 8      h

请输入要读取的行数:
26
第26行的内容是 :
26      z

请输入要读取的行数:
33
第33行的内容是 :
Error 3: 行数超出文件长度。

请输入要读取的行数:
66
第66行的内容是 :
Error 3: 行数超出文件长度。

请输入要读取的行数:
^Z

Process returned 0 (0x0)   execution time : 24.632 s
Press any key to continue.

**********************************/





  • 25
    点赞
  • 144
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值