C++读取中文txt文件,并对文件指定内容进行检测和修改

0.基本知识- fstream文件流进行文件读取与写入

  • 导入库
#include <fstream>
using namespace std;
  • 读入文件
fstream myfile("Information.txt");//能读能写
//ifream 只能读
//ofream 只能写
  • 判断文件是否打开成功
if (!myfile.is_open())
	{
    
    
		cout << "can not open this file" << endl;
		return 0;
	}
  • 判断文件是否读取到末尾
while(!myfile.eof())
  • 逐行将文件内容读入temp中并打印
#include <string>
string temp;
while(!myfile.eof()){
    
    
		getline(myfile,temp);
		cout<<temp;
}
  • 读取文件的指针偏移
myfile.seekp(-3,ios::cur);//put,写指针,从当前位置往前偏移3个字节(L宽字节)
myfile.seekg(-3,ios::cur);//get,读指针
  • 关闭文件
myfile.close();

1.任务

  • 编写一个程序,每次运行会对txt内容进行修改,具体修改如下:有效性:0变为有效性:1,有效性:1变为有效性:0
  • 配套txt文档下载
    在这里插入图片描述

2.方法1

  • 创建一个人容器lines将文档内容全部读入,再写入新文件,通过相同文件名用新文件覆盖旧文件(调试时对应txt编码ansi1)
  • 缺点是时空开销都较高
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main() {
    
    

std::vector<std::string> lines;
std::string line;
std::ifstream file("D:\\ugtrainning\\document\\information.txt");
if (file.is_open())
{
    
    
while (std::getline(file, line))
{
    
    
lines.push_back(line);
}
file.close();
}
else {
    
    
std::cerr << "无法打开文件" << std::endl;
return 1;
}
std::string& line3 = lines[2];
if (line3 == "有效性:1") {
    
    
line3 = "有效性:0";
}
else if (line3 == "有效性:0") {
    
    
line3 = "有效性:1";
}
std::ofstream outfile("D:\\ugtrainning\\document\\information.txt");
if (outfile.is_open()) {
    
    
for (const auto& line : lines)
{
    
    
outfile << line << "\n";
}
outfile.close();
}

return 0;
}

3.方法2

  • 通过读取指针的偏移在检测后原地修改文档内容
  • 缺点是txt编码方式对偏移位数会有影响,需要根据编码方式进行调整
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    
    
    fstream myfile("Information.txt");
	string temp;
	int i1,i2 = 0;
	if (!myfile.is_open())
	{
    
    
		cout << "can not open this file" << endl;
		return 0;
	}
	while(!myfile.eof()){
    
    
		getline(myfile,temp);
		if(i1==2 || i2==18){
    
    
			if(temp[8]=='1'){
    
    
				myfile.seekp(-3,ios::cur);
				myfile<<"0";
				getline(myfile,temp);
			}
			if(temp[8]=='0'){
    
    
				myfile.seekp(-3,ios::cur);
				myfile<<"1";
				getline(myfile,temp);
			}
			i2=0;
		}
		i2++;
		i1++;
	}
	myfile.close();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_53610475/article/details/131138737