C++实现tail -n命令

#include 
#include 
using namespace std;
int iShowFileLastLine(const string &strFileFullPath, int iNeedShowLineNo)
{
	FILE *fp = nullptr;
	if (fopen_s(&fp, strFileFullPath.c_str(), "rb"))
	{
		printf("打开文件失败\n");
		return -1;
	}
	fseek(fp, -1, SEEK_END);//fp移动到文件最后一位
	unsigned int nCount = 0;//当前是倒数第几行
	unsigned char cJudge = { 0 };//判断是否是\n
	unsigned char cContent = { 0 };//读取内容
	while (true)
	{
		fread(&cJudge, 1, 1, fp);
		if (cJudge == '\n')
		{
			nCount++;
			if (nCount == iNeedShowLineNo)
			{//如果正好到规定的行号,则从当前fp输出至文件尾
				while (feof(fp)==0)
				{
					fread(&cContent, 1, 1, fp);
					printf("%c", cContent);
				}
				return 0;
			}
		}
		if (fseek(fp, -2, SEEK_CUR) != 0)//倒序读取,移动文件指针
		{
			printf("超过行数\n");
			return -1;
		}
	}
	fclose(fp);
}
int main()
{
	iShowFileLastLine("C:\\Users\\jm\\Desktop\\test.txt", 3);
	return 0;
}

 

你可能感兴趣的:(c/c++,python,C/C++)