1. 程式人生 > >C/C++ 如何把資料寫到檔案。

C/C++ 如何把資料寫到檔案。

For example:

// 方法一************************************************************************

#include <fstream>

#include <iostream>

using namespace std;

ofstream fout(“filename”); 

fout << num_ <<"  "  ;
fout << channels_ <<"  "  ;
fout << height_ <<"  "  ;
fout << width_ <<"  "  ;
for (int i = 0; i < count_; ++i) {
fout << data_->cpu_data() <<"  "  ;
}
fout.close();

如果想在matlab中讀取,只需Data = load("filename")即可讀取。

// 方法二************************************************************************

FILE* fp = fopen(file_name.c_str(), "wb");
CHECK(fp);
fwrite(&num_, sizeof(int), 1, fp);
fwrite(&channels_, sizeof(int), 1, fp);
fwrite(&height_, sizeof(int), 1, fp);
fwrite(&width_, sizeof(int), 1, fp);
       //fwrite(data_->cpu_data(), sizeof(Dtype), count_, fp); //cpudata
fwrite(mydata, sizeof(Dtype), 10000, fp); //cpudata
fclose(fp);

// *********************************************************************************

Writes data to a stream.

size_t fwrite(
   const void *buffer,
   size_t size,
   size_t count,
   FILE *stream 
);
轉自:http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=EN-US&k=k(stdio%2Ffwrite);k(fwrite);k(DevLang-C%2B%2B);k(TargetOS-Windows)&rd=true