手动实现一个tail命令.默认输出十行.假如文件小于十行,则将文件全部输出.也可指定输出的行数.假如指定的行数超过了文件行数上限,则完整输出整个文件.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void tail(const char *filename,int count = 10)
{
int realline = 0;
char temp;
string stackstr("");
ifstream fd(filename);
if(!fd)
{
cerr<<"open error!"<<endl;
return;
}
while(fd.get(temp))
{
stackstr += temp;
if(temp == '\n')
realline++;
}
int j = 0;
if(realline > count)
{
while(j < stackstr.length())
{
if(count == realline)
{
cout<<stackstr[j];
}
else
{
if(stackstr[j] == '\n')
count ++;
}
j++;
}
}
else
{
while(j < stackstr.length())
{
cout<<stackstr[j];
j++;
}
}
}
int main(int argc,char**argv)
{
tail("C:\\Users\\fjy\\Desktop\\new.txt",5);
return 0;
}
tail函数第一个参数指定文件名,第二个参数指定输出的行数,默认为10.
|