c++ 讀寫文件總結


在此之前我已經分別使用過這兩種方法,我這里沒有重新寫代碼,只po上我之前實際使用的

頭文件都是<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++的例子搬過來

文本讀:

//采用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

文本寫:

//采用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

二進制讀:

//采用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

二進制寫:

//采用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中seekg()和seekp()的用法 

seekg()/seekp()與tellg()/tellp()的用法詳解

我自己補充了個完整的例子:

#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

其中123.txt

123out.txt

效果是覆蓋不是插入

博客五c++ 二進制文件讀寫 這篇是我之前寫的博客,那時要格式化的讀寫二進制文件,這個是留着我自己看的(因為我寫了幾篇c++讀寫的博客,以后我打算只看這篇了)

讀取圖片保存至binary.dat二進制文件

//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並進行特征比對

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM