逐行读取文件内容的三种方法

测试用数据:



方法一:采用Getline函数

ifstream in("1.txt");  
	string line;  
	
	int i = 0;

	if(in) // 有该文件  
	{  
		while (getline (in, line)) // line中不包括每行的换行符  
		{   
			cout << line<<"    "<<i++<<endl;   
		}  
	}  
	else // 没有该文件  
	{  
		cout <<"no such file" << endl;  
	}  

	return 0;


方法二、采用fscanf进行格式化读取

char szSrcFile[_MAX_PATH] = {0},szDstFile[_MAX_PATH] = {0};

	FILE* fp = fopen("1.txt", "rt");

	if (fp)
	{
		while(EOF != fscanf(fp, "%s\t%s\n", szSrcFile, szDstFile))
		{
			cout<<szSrcFile<<"  "<<szDstFile<<endl; 
		}

		fclose(fp);
		fp = NULL;
	}
	else{
		cout<<"fopen() error !"<<endl;
	}


方法三:

char szbuf[MAX_PATH] = {0};

	FILE* fp = fopen("1.txt", "rt");

	if (fp)
	{
		while (fgets(szbuf,MAX_PATH,fp) != NULL)
		{
			cout<<szbuf;
		}

		fclose(fp);

		fp = NULL;
	} 
	else
	{
		cout<<"打开文件失败!"<<endl;
	}




发布了415 篇原创文章 · 获赞 123 · 访问量 64万+

猜你喜欢

转载自blog.csdn.net/u012372584/article/details/77658621