C++ read file
There are two ways to realize the function of reading files.
The first one:
use fread to realize this method, which is suitable for reading various structured data packets.
#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <string.h>
int main(){
FILE *file_pointer = fopen("/home/data/abc.dat", "rb");
//假设数据包abc.dat中存储的是DiyInfo类型的结构体
DiyInfo diy_info;
while (!feof(file_pointer)) {
//从数据文件中读取数据,放入diy_info中进行反序列化
fread(&diy_info, sizeof(char), sizeof(DiyInfo), file_pointer);
//打印读出来的结果
printf(diy_info.xxxxx);
}
fclose(file_pointer);
return 0;
}
The second method:
implemented with fstream, this method is suitable for reading text files line by line
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
using namespace std;
//解析一行文本的函数,可以将一行字符串按照空格打断,把里面的词取出来装进vector向量
vector<string> parseLine(string line) {
vector<string> v;
int pos = 0;
int pos2 = 0;
int len = line.length();
while (pos < len) {
pos2 = line.find(" ", pos);
if (pos2 == -1)
pos2 = len;
v.push_back(line.substr(pos, pos2 - pos));
pos = pos2 + 1;
}
return v;
}
int main(){
ifstream input_file("/home/data/abc.txt");
string line;
//用getline()函数取出文件中的一行,存入字符串变量line中
while (getline(input_file, line)) {
//line是一大串字符串,如果需要把里面的词拿出来,就调用上面的parseLine函数
vector<string> line_content = parseLine(line);
//依次打印解出来的行中的单词
for (int i = 0; i < line_content.size(); ++i) {
cout << line_content[i] << " ";
}
cout << endl;
}
input_file.close();
return 0;
}
C++ write file
Similarly, there are two ways to achieve
the first:
use fwrite, this method is suitable for writing structured data packets
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
int main(){
FILE* file_pointer = fopen("./testfile.dat", "w");
//假设要在数据包中写入DiyInfo类型的结构体
DiyInfo diy_info;
//向文件中写入1000帧
for (int i = 0; i < 1000; ++i){
diy_info.xxxxx = 777;
fwrite(&diy_info, 1, sizeof(DiyInfo), file_pointer);
}
fclose(file_pointer);
return 0;
}
The second method:
implement with fstream, this method is suitable for writing text files line by line, very simple, almost exactly the same as cout
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
using namespace std;
int main(){
std::ofstream output_file("./testfile.dat");
DiyInfo diy_info;
for (int i = 0; i < 1000; ++i){
diy_info.xxxxx = i;
output_file << "diy_info.xxxxx " << diy_info.xxxxx << endl;
cout << "diy_info.xxxxx " << diy_info.xxxxx << endl;
}
outfile.close();
return 0;
}