C/C++ 如何把数据写到文件。

本文介绍两种使用C++进行文件写入的方法,并说明如何在Matlab中加载这些文件。第一种方法利用ofstream类将数据逐项写入文本文件;第二种方法采用fwrite函数将数据写入二进制文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 
);

Parameters

buffer

Pointer to data to be written.

size

Item size, in bytes.

count

Maximum number of items to be written.

stream

Pointer to FILE structure.

转自: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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值