C++C IO操作帮助函数
每次操作文本时总是每次手动写,干脆直接总结一下。以后可以直接在这里抄一下就行。
头文件部分在:
/**
* 读文本文件(单列)
*/
std::vector<std::string> read_lines(const char* file_path);
/**
* 读文本文件(多列)
std::string[] columns = { "column1", "column2" };
*/
std::vector<std::vector<std::string>> read_lines(const char* file_path, std::string columns[], char delimiter);
/**
* 写文本文件(单列)
*/
void write_lines(const char* file_path, std::vector<std::string> lines);
/**
* 写文本文件(多列)
*/
void write_lines(const char* file_path, std::vector<std::vector<std::string>> lines, char delimiter);
/**
* C++写入对象(也支持class, 但是属性中必须是不带指针的)
参考:https://blog.csdn.net/LearnLHC/article/details/88895110
https://blog.csdn.net/bladeandmaster88/article/details/53217736
https://www.cnblogs.com/marky/p/3709250.html
如:typedef struct { int age; char[] name; } Person;
Person zhangsan;
zhangsan.age=18; zhangsan.name="zhangsan";
anjos_write("demo.bin", reinterpret_cast<char*>(&zhangsan), sizeof(zhangsan));
*/
void stream_write(const char* file_path, char* x, int len);
/**
* C++读取对象
如 typedef struct { int age; char[] name; } Person;
char * temp = anjos_read("demo.bin", sizeof(Person));
Person zhangsan = *(Person*)(temp);
delete[] temp;
转换后记得要释放这个char*
*/
char* stream_read(const char* file_path, int len);
实现部分在这:
std::vector<std::string> read_lines(const char* file_path) {
std::ifstream is(file_path);
std::string line;
std::vector<std::string> lines;
if (is) {
while (getline(is, line)) {
lines.push_back(line);
}
is.close();
}
return lines;
}
std::vector<std::vector<std::string>> read_lines(const char* file_path, std::string columns[], char delimiter) {
std::ifstream is(file_path);
std::string line;
std::vector<std::vector<std::string>> lines;
if (is) {
while (getline(is, line)) {
std::vector<std::string> arr;
split(line, arr, delimiter);
lines.push_back(arr);
}
is.close();
}
return lines;
}
void write_lines(const char* file_path, std::vector<std::string> lines) {
std::ofstream os(file_path, std::ios::out);
for (std::string line : lines) {
os << line << std::endl;
}
os.close();
}
void write_lines(const char* file_path, std::vector<std::vector<std::string>> lines, char delimiter = '\t') {
std::ofstream os(file_path, std::ios::out);
std::string delimiter_str(delimiter+""); // std::cout打印不出char
for (std::vector<std::string> arr : lines) {
for (int i = 0, len = arr.size(); i < len; i++) {
if (i == len - 1) {//最后一个元素
os << arr[i] << std::endl;
} else {
os << arr[i] << delimiter_str;
}
}
}
os.close();
}
void stream_write(const char* file_path, char* x, int len) {
std::ofstream os(file_path, std::ios::out | std::ios::binary);
os.write(x, len);
os.close();
}
char* stream_read(const char* file_path, int len) {
std::ifstream is(file_path, std::ios::in | std::ios::binary);
char* temp = new char[len];
if (is) {
is.read(temp, len);
}
is.close();
return temp;
}