现在的位置: 首页 > 综合 > 正文

用C++的方式读取并显示文件的每一行

2013年03月31日 ⁄ 综合 ⁄ 共 512字 ⁄ 字号 评论关闭

 

#include <stdio.h>
#include <fstream>
using namespace std;

bool FileGetLine(const char* szFileName)
{
	bool fRet = false;
	int iLineIndex = 0;

	const int MAX_LINE_LEN = 512;
	static char szLineData[MAX_LINE_LEN];

	ifstream infile;
	infile.open(szFileName);
	if ( !infile.fail() )
	{
		while (true)
		{
			infile.getline(szLineData, MAX_LINE_LEN);
			if ( infile.eof() )
			{
				fRet = true;
				break;
			}
			else
			{
				printf("%03d:[%s]\n", ++iLineIndex, szLineData);
			}
		}

		infile.close();
	}

	return fRet;
}

int main(void)
{
	if ( true == FileGetLine("demo.txt") )
	{
		printf("ok\n");
	}
	else
	{
		printf("on!\n");
	}

	getchar();
	return 0;
}

抱歉!评论已关闭.