c++ 读写文件总结

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

头文件都是<fstream>

方法一:

c++ <fstream> 读写文件总结

c++ <fstream> 读写文件总结

方法二:

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

 

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

博客一C++中简单的文本文件输入/输出  入门首选,但读写的格式类型比较简单了,稍微复杂一点就需要用结构体

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

文本读:

c++ <fstream> 读写文件总结

//采用CPP模式读取txt
void 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<int> index;
    vector<double> x_pos;
    vector<double> y_pos;
    if(!f)
    {
        cout << "打开文件出错" << endl;
        return;
    }
    cout<<"mode为1,按字符读入并输出;mode为2,按行读入输出;mode为3,知道数据格式,按行读入并输出"<<endl;
    int mode = 1;
    cin>>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

文本写:

c++ <fstream> 读写文件总结

//采用CPP模式写txt
void 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" <<setw(10)<< y_pos[i] << endl;
    f.close();
 
}

View Code

二进制读:

c++ <fstream> 读写文件总结

//采用CPP模式读二进制文件
void DataRead_CPPMode()
{
    double pos[200];
    ifstream f("binary.dat", ios::binary);
    if(!f)
    {
        cout << "读取文件失败" <<endl;
        return;
    }
    f.read((char*)pos,200*sizeof(double));
    for(int i = 0; i < 200; i++)
        cout << pos[i] <<endl;
    f.close();
 
}

View Code

二进制写:

c++ <fstream> 读写文件总结

//采用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 << "创建文件失败" <<endl;
        return;
    }
    f.write((char*)pos, 200*sizeof(double));      //fwrite以char *的方式进行写出,做一个转化
    f.close();
}

View Code

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

c++ <fstream> 读写文件总结

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

c++ fstream中seekg()和seekp()的用法 

seekg()/seekp()与tellg()/tellp()的用法详解

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

c++ <fstream> 读写文件总结

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

    in.seekg(-sp/3,ios::end);
    streampos sp2=in.tellg();
    cout<<"from file to point:"<<endl<<sp2<<endl;

    in.seekg(0,ios::beg);
    cout<<in.rdbuf();

    in.seekg(sp2);
    cout<<in.rdbuf()<<endl;

    //output
    ofstream out("123out.txt");
    assert(out);
    out.seekp(0,ios::beg);
    out<<"happy christmas";
    cout<<"filesize:"<<endl<<out.tellp()<<endl;

    out.seekp(-9,ios::end);
    out<<"birthday";
    cout<<"filesize:"<<endl<<out.tellp()<<endl;

    return 0;
}

View Code

c++ <fstream> 读写文件总结

其中123.txt

c++ <fstream> 读写文件总结

123out.txt

c++ <fstream> 读写文件总结

效果是覆盖不是插入

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

c++ <fstream> 读写文件总结

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

c++ <fstream> 读写文件总结

//write binary.dat
void img2dat(){
    struct dirent *ptr, *ptr1;
    DIR *dir, *dir1;
    dir = opendir("../lfw_crop/");

    string file_path, temp;
    std::vector<Anchor> 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<<temp<<endl;
            Mat face = mt(img, result_copy, count);
            if (count){
                fea = extract_feature(face);
                for(int i=0;i<128;i++)
                    face_temp[num].fea[i] = fea[i];
                outFile.write((char*)&face_temp[num], sizeof(face_temp[num]));
                cout<<++num<<endl;
            }
            //just one img
            break;
        }
        closedir(dir1);
    }
    closedir(dir);
    outFile.close();
}

View Code

读binary.dat并进行特征比对

c++ <fstream> 读写文件总结

if(count)
        {
            clock_t start_2, finish_2;
            start_2 = clock();
            vector<float> 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 <<endl <<endl;
        }

View Code

原文链接: https://www.cnblogs.com/exciting/p/11165535.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++ <fstream> 读写文件总结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/298519

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午7:51
下一篇 2023年2月15日 下午7:51

相关推荐