TXT文件的读取以及编辑(C++)实现

TXT文件的读取以及编辑(C++)实现
//代码说明书
1 在头文件创建txtAccessor类,在源文件采用简单的菜单形式调用
2 txtAccessor有四个功能,txt文件的存、取、编辑、打印
3 存取需要输入文件名
4 编辑是对之前内容的续写,编辑以换行+end结束
5 隐藏功能,通过连续两次读文件可以实现文件合并

源文件

#include<iostream>
#include <string>
#include"txtAccessor.h"
using namespace std;
int main()
{
	txtAccessor T;    //create a txtAccessor object
	string file;      // name of file
	cout << "-----------------------menu-----------------------\n";     
	cout << "0 exit    1 read     2 print    3 edit     4 write\n";
	int index;        //function index
	while (1) {
		cin >> index;
		if (index == 0)break;
		switch (index)
		{
		case 1:cin >> file; T.getTxt(file); break;  //需要输入读取的文件名
		case 2:T.printTxt(); break;
		case 3:T.editTxt(); break;                  //以换行+end结束编辑
		case 4:cin >> file; T.writeTxt(file); break;//需要输入写入的文件名
		default:break;
		}
	}
	return 0;
}

头文件

pragma once
#include<iostream>
#include<fstream>
#include<vector>
#include <string>
#define maxWordsCount 1000    //编辑时每次可添加的最大字数
using namespace std;

/*txt存取器,实现txt文件的读取写入与编辑*/
class txtAccessor {
private:
	vector<string> txt;
public:
	txtAccessor() {};
	txtAccessor(string file);   //p初始化时读入
	void getTxt(string file);   //获取txt文本
	void printTxt();            //打印
	void editTxt();             //编辑
	void writeTxt(string file); //保存
};

txtAccessor::txtAccessor(string file) {
	ifstream infile;
	infile.open(file.data());
	if (!infile.is_open()) {
		cout << "Couldn't open file";
		exit(-1);
	}
	string t;
	while (getline(infile, t)) {      //按行读取
		txt.push_back(t);
	}
	infile.close();
}
void txtAccessor::getTxt(string file) {  //与带参的构造函数功能相同,用于未初始化txtAccessor的读取
	ifstream infile;
	infile.open(file.data());
	if (!infile.is_open()) {
		cout << "Couldn't open file";
		exit(-1);
	}
	string t;
	while (getline(infile, t)) {
		txt.push_back(t);
	}
	infile.close();
}
void txtAccessor::printTxt() {
	for (int i = 0; i < txt.size(); i++) {
		cout << txt[i] << endl;                 //按行输出,与按行读取对应
	}
}
void txtAccessor::editTxt() {
	int flag = 0;                   //因为下边的gets_s()函数第一次调用时自动传入一个空格,导致编辑前后空了一行,所以设置flag使循环从第二次开始read
	char t[maxWordsCount];
	while (1) {
		gets_s(t, maxWordsCount);
		if (!strcmp(t,"end"))break;  //用换行+end结束edit
		if(flag)txt.push_back(t);
		flag = 1;
	}
}
void txtAccessor::writeTxt(string file){
	ofstream outfile(file.data());
	if (!outfile.is_open()) {
		cout << "Failure to create file\n";
	}
	for (int i = 0; i < txt.size(); i++) {
		outfile << txt[i] << endl;         //同样是按行write
	}
}

运行结果
因为用c++的面向对象实现,所以看了起来比较麻烦,毕竟是训练自己面向对象设计的思想。代码通俗易懂,不需要解释什么,主要运用C++输入输出流的相关知识。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值