博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++ <fstream> 读写文件总结
阅读量:4696 次
发布时间:2019-06-09

本文共 6127 字,大约阅读时间需要 20 分钟。

在此之前我已经分别使用过这两种方法,我这里没有重新写代码,只po上我之前实际使用的

头文件都是<fstream>

方法一:

方法二:

fstream pos("./pos_scores.txt", fstream::in | fstream::out | fstream::trunc);...pos << pair_id <<"\t"<< cal << "\t" <
<<"\t"<
<

 

头文件都是<fstream>两种方法应该是接近一样的,所以我去网上找了更好的总结

博客一:  入门首选,但读写的格式类型比较简单了,稍微复杂一点就需要用结构体

博客二: 我的第一个读写二进制文件写法就抄的这里,我觉得c++的写法更简洁,所以我会将c++的例子搬过来

文本读:

//采用CPP模式读取txtvoid TextRead_CPPmode(){    fstream f;    f.open("txt_out.txt",ios::in);        //文件打开方式选项:    // ios::in    = 0x01, //供读,文件不存在则创建(ifstream默认的打开方式)    // ios::out    = 0x02, //供写,文件不存在则创建,若文件已存在则清空原内容(ofstream默认的打开方式)    // ios::ate    = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用    // ios::app    = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入新的内容,指针位置总在最后    // ios::trunc   = 0x10, //在读写前先将文件长度截断为0(默认)    // ios::nocreate = 0x20, //文件不存在时产生错误,常和in或app联合使用    // ios::noreplace = 0x40, //文件存在时产生错误,常和out联合使用    // ios::binary  = 0x80  //二进制格式文件    vector
index; vector
x_pos; vector
y_pos; if(!f) { cout << "打开文件出错" << endl; return; } cout<<"mode为1,按字符读入并输出;mode为2,按行读入输出;mode为3,知道数据格式,按行读入并输出"<
>mode; if(1== mode) { //按字节读入并输出 char ch; while(EOF != (ch= f.get())) cout << ch; } else if(2 == mode) { //按行读取,并显示 char line[128]; int numBytes; f.getline(line,128); cout << line << "\t" << endl ; f.getline(line,128); cout << line << "\t" << endl ; f.seekg(0,0); //跳过字节 //seekg(绝对位置);      //绝对移动,    //输入流操作 //seekg(相对位置,参照位置);  //相对操作 //tellg(); //返回当前指针位置 while(!f.eof()) { //使用eof()函数检测文件是否读结束 f.getline(line,128); numBytes = f.gcount(); //使用gcount()获得实际读取的字节数 cout << line << "\t" << numBytes << "字节" << endl ; } } else if(3 == mode) { //如果知道数据格式,可以直接用>>读入 int index_temp = 0; double x_pos_temp = 0, y_pos_temp = 0; while(!f.eof()) { f >> index_temp >> x_pos_temp >> y_pos_temp ; index.push_back(index_temp); x_pos.push_back(x_pos_temp); y_pos.push_back(y_pos_temp); cout << index_temp << "\t" << x_pos_temp << "\t" << y_pos_temp << endl; } } f.close();}
View Code

文本写:

//采用CPP模式写txtvoid TxtWrite_CPPmode(){    //准备数据    int index[50] ;    double x_pos[50], y_pos[50];    for(int i = 0; i < 50; i ++ )    {        index[i] = i;        x_pos[i] = rand()%1000 * 0.01 ;        y_pos[i] = rand()%2000 * 0.01;    }    //写出txt    fstream f("txt_out.txt", ios::out);    if(f.bad())    {        cout << "打开文件出错" << endl;        return;    }    for(int i = 0; i < 50; i++)        f << setw(5) << index[i] << "\t" << setw(10) << x_pos[i] <<"\t" <
<< y_pos[i] << endl; f.close(); }
View Code

二进制读:

//采用CPP模式读二进制文件void DataRead_CPPMode(){    double pos[200];    ifstream f("binary.dat", ios::binary);    if(!f)    {        cout << "读取文件失败" <
View Code

二进制写:

//采用CPP模式写二进制文件void DataWrite_CPPMode(){    //准备数据    double pos[200];    for(int i = 0; i < 200; i ++ )        pos[i] = i ;    //写出数据    ofstream f("binary.dat",ios::binary);    if(!f)    {        cout << "创建文件失败" <
View Code

博客三: 使用上面四个代码的格式,需要指定文件打开模式

教程四:,适合入门,每个都讲了点但是不完整

 

我自己补充了个完整的例子:

#include 
#include
#include
using namespace std;int main(){ //input ifstream in("123.txt"); assert(in); in.seekg(0,ios::end); streampos sp=in.tellg(); cout<<"filesize:"<
<
<
View Code

其中123.txt

123out.txt

效果是覆盖不是插入

博客五: 这篇是我之前写的博客,那时要格式化的读写二进制文件,这个是留着我自己看的(因为我写了几篇c++读写的博客,以后我打算只看这篇了)

读取图片保存至binary.dat二进制文件

//write binary.datvoid img2dat(){    struct dirent *ptr, *ptr1;    DIR *dir, *dir1;    dir = opendir("../lfw_crop/");    string file_path, temp;    std::vector
result_copy; int num = 0,count = 1; ofstream outFile("binary.dat", ios::out | ios::binary); Face face_temp[6000]; // printf("lists of files:\n"); while((ptr = readdir(dir)) != NULL){ if(ptr->d_name[0] == '.') continue; //search subdirectory char sub_dir[50] = "../lfw_crop/"; strcpy(face_temp[num].name, ptr->d_name); strcat(sub_dir, ptr->d_name); file_path = sub_dir; dir1 = opendir(sub_dir); while((ptr1 = readdir(dir1)) != NULL){ if(ptr1->d_name[0] == '.') continue; temp = ptr1->d_name; file_path = file_path + "/" + temp; cv::Mat img = imread(file_path); count = 1; cout<
<
View Code

读binary.dat并进行特征比对

if(count)        {            clock_t start_2, finish_2;            start_2 = clock();            vector
feature2 = extract_feature(face2); finish_2 = clock(); cout << "mobilefacenet cost " << (float)(finish_2 - start_2) / CLOCKS_PER_SEC * 1000 << " ms" << endl; //2019.6.12 int i=0, num=0; double curcal, max=0; string forecast_name; //2019.6.17 // float fea[128]; string name; clock_t start_3, finish_3; start_3 = clock(); Face face_temp[6000]; while(inFile.read((char *)&face_temp[num], sizeof(face_temp[num]))){ curcal = calculSimilar(feature2, face_temp[num].fea); if(curcal > max){ max = curcal; forecast_name = face_temp[num].name; } } finish_3 = clock(); cout << "search binary.dat cost & calculSimilar:" << (float)(finish_3 - start_3) / CLOCKS_PER_SEC * 1000 << " ms" << endl; cout << "max similarity is: "<< max << endl; cout << "forecast name is: "<< forecast_name <
<
View Code

转载于:https://www.cnblogs.com/exciting/p/11165535.html

你可能感兴趣的文章
mysql DML DDL DCL
查看>>
RAMPS1.4 3d打印控制板接线与测试1
查看>>
python with语句中的变量有作用域吗?
查看>>
24@Servlet_day03
查看>>
初级ant的学习
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>
[CCF2015.09]题解
查看>>
[NYIST15]括号匹配(二)(区间dp)
查看>>
json_value.cpp : fatal error C1083: 无法打开编译器生成的文件:No such file or directory
查看>>
洛谷 P1101 单词方阵
查看>>