一、背景
之前遗留了一个问题,就是c++没有文件创建文件的代码,这边整理一下,下次可以直接使用
二、实现
#include <iostream>
#include <fstream>
#include <vector>
#define PATH_SEPARATOR_CHAR '/'
#define PATH_SEPARATOR_STR "/"
using namespace std;
bool checkFileExist(const string &filePath) {
fstream fs;
fs.open(filePath, ios::in);
if (!fs) {
cout << "不存在该文件" << endl;
ofstream out(filePath);
if (out) {
//创建成功
cout << "创建成功" << endl;
} else {
//创建失败
cout << "创建失败" << endl;
return false;
}
} else {
cout << "文件已存在" << endl;
}
return true;
}
std::string GetProjectPath() {
std::string currentFilePath(__FILE__);
string str = currentFilePath.substr(0, currentFilePath.find_last_of('/'));
return str;
}
std::string JoinPath(const std::string &existPath, const std::string &newPart)
{
if (existPath.back() == PATH_SEPARATOR_CHAR || existPath.empty()) {
return existPath + newPart;
}
return existPath + PATH_SEPARATOR_STR + newPart;
}
void writeRateToTxt(const vector<string> &infoVector) {
string path = GetProjectPath();
string fileName = "resultData.txt";
string filePath = JoinPath(path, fileName);
if (!checkFileExist(filePath)) {
return;
}
fstream fs;
fs.open(filePath, ios::in | ios::app);
for (vector<string>::const_iterator it = infoVector.begin(); it != infoVector.end(); it++) {
fs << *it << endl;
}
fs.close();
}
int main()
{
vector<string> vec(2);
vec[0] = "jim";
vec[1] = "kevin";
writeRateToTxt(vec);
}
上述的代码实现了写文件的过程,没有文件就创建文件并写文件。需要着重指出的是ios::app是续写。
实现效果
jim
kevin
但是这边还遗留一个问题,就是重新写的时候怎么清除文件中的内容。帖子说的方法是ios::trunc。但是实验了好像不行。
三、总结
未完待续