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;
}