`

C++文件行查找

阅读更多

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

void usage(const char* szExe)
{
	cout << "usage:" << szExe << " <file path> <file string> <print type>" << endl;
	cout << "<print type>: 0|1|2  0:print all 1:print first 2:print last" << endl;
	cout << "example: " << szExe << "./a.log \"hello,andylin\" 0" << endl;
}

int FileFindContent(const char* szFile, const char* szFind, const int nFindType)
{
	ifstream fin(szFile);
	if (!fin)
	{
		cout << "open file failed!" << endl;
		return -1;
	}

	string strLine = "";
	string strResult = "";
	while (getline(fin, strLine))
	{
		if (-1 != strLine.find(szFind))
		{
			if (0 == nFindType)
			{
				cout << strLine << endl;
			}
			else if (2 == nFindType)
			{
				strResult = strLine;
			}
			else
			{
				cout << strLine << endl;
				return 0;
			}
		}
	}

	if (2 == nFindType)
	{
		cout << "Find Last Line:" << endl;
		cout << strResult << endl;
	}

	return 0;
}

int main(int argc, char** argv)
{
	if (4 != argc)
	{
		usage(argv[0]);
		return 1;
	}

	char* szFile = argv[1];
	char* szFind = argv[2];
	int nFindType = atoi(argv[3]);

	return FileFindContent(szFile, szFind, nFindType);
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics