给文件加行号的小程序

 程序名strFile
在linux环境下输入shell命令:
./strFlie filename1 [filename2]
将filename每行加上行号,输出到filename2中,若没有设置参数2,filename2=~filename1
strFile.cpp:
#include  < sys / stat.h >
#include 
< iostream >
#include 
< fstream >
#include 
< cstddef >
#include 
< cstdlib >
#include 
< string >

using namespace std;

class Cmyfile
{
private:

    string fName;
    size_t rowNum;
public:
        ifstream infile;
    Cmyfile(string str);
    
~Cmyfile();
    string getFileName();
    bool getLine(string
& line);
    
}
;

Cmyfile::Cmyfile(string str):fName(str),rowNum(
0 ),infile(str.c_str())
{
    
if(!infile)
    
{
        cerr
<<"Cannot open "<<fName<<"!"<<endl;
        exit(
0);
    }

}


Cmyfile::
~ Cmyfile()
{}

string Cmyfile::getFileName()
{
    
return fName;
}


bool Cmyfile::getLine(string
&  line)
{
    
if(getline(infile,line))
      
return true;
    
return false;
}


int  main( int  argc, char *  argv[])
{
    
if(argc==1)
    
{
        cerr
<<"Please input the file name!"<<endl;
        exit(
0);
    }


    Cmyfile thefile(argv[
1]);
    string outf(
"~");
    
if(argc>1)
        outf
=string(argv[2]);
    
else
        outf
+=argv[2];
    ofstream outfile(outf.c_str());
    string eline;
    
int icout=0;
    
while(thefile.getLine(eline))
    
{
        
char s[10],t[10];
        sprintf(s,
"/*%d*/",icout);
        sprintf(t,
"%-10s",s);
        eline.insert(
0,t);
        outfile
<<eline<<endl;
        
++icout;
    }

    cout
<<"the primary file: "<<thefile.getFileName()<<endl;
    cout
<<" the dealed file: "<<outf<<endl;
}

结果示例:
/*0*/      #include  < sys / stat.h >
/*1*/      #include  < iostream >
/*2*/      #include  < fstream >
/*3*/      #include  < cstddef >
/*4*/      #include  < cstdlib >
/*5*/      #include  < string >
/*6*/      
/*7*/       using   namespace  std;
/*8*/      
/*9*/       class  Cmyfile
.....
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值