实验E1:命令行工具fcmd,实验对文本的操作

fcmd.h

#pragma once
#include <string>

void print(const std::string& filename);

void format(const std::string& filename);

void addWord(const std::string& filename);

fcmd.cpp

#include "fcmd.h"
#include <fstream>
#include <iostream>

static bool openFile(const std::string& filename, std::ios::_Openmode iosMode, std::fstream& iofile)
{
	iofile.open(filename, iosMode);
	if (!iofile.is_open())
	{
		std::cout << "文件打开失败。" << std::endl;
		return false;
	}
	return true;
}

void print(const std::string& filename)
{
	std::fstream infile;
	if (!openFile(filename, std::ios::in, infile))
		return;
	std::string line;
	while (std::getline(infile, line))
		std::cout << line << '\n';
	infile.close();
}

void format(const std::string& filename)
{
	//读文件
	std::fstream infile;
	if (!openFile(filename, std::ios::in, infile))
		return;
	std::string str, temp;
	while (infile >> temp)
		str += (temp + " ");
	infile.close();

	//格式化
	size_t pos = 0;
	while (pos != str.size()) //标点前后加空格
	{
		if (ispunct(str[pos]) ) //单引号不换可能好看点
		{
			str.insert(pos + 1, " ");
			if (pos > 0)
				str.insert(pos, " ");
			pos++;
		}
		pos++;
	}
	pos = -1;
	while ((pos = str.find("\n", pos + 1)) != std::string::npos) //换行全部换成空格,这些操作是为了避免呈现形式错误 
		str[pos] = ' ';
	pos = 0;
	while ((pos = str.find("  ", pos)) != std::string::npos) //换成单空格
		str.replace(pos, 2, " ");
	pos = 0;
	while ((pos = str.find(" ", pos + 1)) != std::string::npos) //单空格换成换行
		str[pos] = '\n';

	//将修改后的文件写回去 
	std::fstream outfile;
	if (openFile(filename, std::ios::out, outfile))
		outfile << str;
	outfile.close();
}

void addWord(const std::string& filename)
{
	std::fstream outfile;
	if (openFile(filename, std::ios::app, outfile))
		outfile << "\nthese are random words" << std::endl;
	outfile.close();
}

main

#include <string>
#include "fcmd.h"

int main(int argc, char* argv[])
{
	if (argc >= 2)
	{
		std::string cmd = argv[1];
		std::string filename = (argc > 2 ? argv[2] : "test.txt");
		if (cmd == "print")
			print(filename);
		else if (cmd == "format")
			format(filename);
		else if (cmd == "addword")
			addWord(filename);
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值