c++读取和写入TXT文件的整理方法分享!

如下所示:

  #include "stdafx.h"  #include <iostream>   //无论读写都要包含<fstream>头文件  #include <fstream>   #include <iomanip>   using namespace std;     int main()  {  	//ifstream从文件流向内存的ifstream表示文件输入流,意味着文件读操作  	ifstream myfile("c://a.txt");  	//ofstream从内存流向文件的ofstream表示文件输出流,意味着写文件操作  	ofstream outfile("c://b.txt");     	fstream fin1("file1.txt", ios::in);           	/*********************************************************************************************************/  	//读文件的例子  	//如果文件不存在(在visual stdio 2017环境下,文件存在了有.vcxproj文件的那个文件夹里面)  	if (!fin1) {     		//试了一下,用cout也可以,现在我还不明白为什么用cerr,为什么标准库要定义cerr这个对象  		cerr << "读取失败" << endl;  		system("pause");  		return -1;  	}  	else {  		cout << "读取成功" << endl;  		//说明文件非空  		if (outfile.is_open())  		{  			char linestring[100];     			//memset函数在socket中多用于清空数组.如:原型是memset(buffer, 0, sizeof(buffer))  			//memset(linestring, 0, 100);     			//file.good()是在文件读取或者写的过程中出现错误,或者读到文件最后继续读才会返回false;  			//eof在读取完最后一个数据后,仍是False,当再次试图读一个数据时,  			//由于发现没数据可读了,才知道到末尾了,此时才修改标志,eof变为True  			if (myfile.good() && !myfile.eof()) {     				// 读取info.txt的一行,存入linestring  				myfile.getline(linestring, 100);     				//对字符一个一个的处理,直到遇到'/0'为止   				for (int i = 0; linestring[i] != 0; i++)    					//通过ASCII码,保证输入的字符是字符   					if (linestring[i] >= 65 && linestring[i] <= 90 || linestring[i] >= 97 && linestring[i] <= 122) {   						//将字母字符存入磁盘文件   						outfile.put(linestring[i]);  						cout << linestring[i] << "";  					}  				cout << endl;  				outfile.close();  			}			  		}	  	}        	/*********************************************************************************************************/  	//写文件的例子  	char ch;  	//以输入的方式打开文件   	ifstream infile("f1.dat", ios::in);      	//如果文件不存在  	if (!infile) {  		cerr << "open error!" << endl;  		exit(1);  	}  	//定义输出流f3.dat文件   	ofstream outfile("f3.dat");   	if (!outfile) {  		cerr << "open error!" << endl;  		exit(1);  	}  	//当读取字符成功时    	while (infile.get(ch)) {  		if (ch <= 122 && ch >= 97)  			ch = ch - 32;  		outfile.put(ch);  		cout << ch;  	}  	cout << endl;  	infile.close();  	outfile.close();     	system("pause");     	return 0;  }     

以上这篇c++读取和写入TXT文件的整理方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持<计算机技术网(www.ctvol.com)!!>。

—-想了解c++读取和写入TXT文件的整理方法分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/482450.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐