C++读写文本
软件开发中经常会有遇到用于交换数据的文本的读写,常常我们会引用json库进行json文件格式的读写,本文记录一下常用的普通文本的读写.
1.读取空格分隔的文本
test.txt 本文内数据用空格分隔:
/*
* test.txt:
* 11 22 33
* 44 55 66
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string fileName = "D:\\test.txt";
std::ifstream fin(fileName.c_str(), std::ios::in);
char line[512] = { 0 };
while (fin.getline(line, sizeof(line))) { // 每行内容读取到字符数组line中
std::stringstream ss(line);
if (ss.rdbuf()->in_avail() != 0) { //避免读入空行
int n1, n2, n3;
ss >> n1;
ss >> n2;
ss >> n3;
cout << n1 << " " << n2 << " " << n3 << endl;
}
}
fin.close();
}
/*
* 控制台打印:
* 11 22 33
* 44 55 66
*/
2.读取符号分隔的(逗号为例)文本
test.txt 本文内数据用’,'分隔:
/*
* test.txt:
* 11, 22, 33
* 44, 55,66
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string fileName = "D:\\test.txt";
std::ifstream fin(fileName.c_str(), std::ios::in);
char line[512] = { 0 };
while (fin.getline(line, sizeof(line))) { // 每行内容读取到字符数组line中
string strline = line;
for (size_t i = 0; i < strline.length(); ++i) {
if (',' == line[i]) {
line[i] = ' ';
}
}
std::stringstream ss(line);
if (ss.rdbuf()->in_avail() != 0) { //避免读入空行
int n1, n2, n3;
ss >> n1;
ss >> n2;
ss >> n3;
cout << n1 << " " << n2 << " " << n3 << endl;
}
}
fin.close();
}
/*
* 控制台打印:
* 11 22 33
* 44 55 66
*/
3.写入文本
ofstream fout;
string fileName = "E:\\test.txt";
fout.open(fileName.c_str(), ios_base::out);
//fout.open(fileName.c_str(), ios::app); //追加方式
if (fout.is_open()) {
fout << "It's me Mario!\n";
}
fout.close();
/*
* test.txt:
* It's me Mario!
*/