C++ ifstream

std::ifstream

參考std::ifstream

Input stream class to operate on files.

Objects of this class maintain a filebuf object as their internal stream buffer, which performs input/output operations on the file they are associated with (if any).

File streams are associated with files either on construction, or by calling member open.

std::ifstream這個類別的物件會對與它關聯的檔案進行操作。

constructor

其建構子的簽名:

/*default (1)*/	
ifstream();
/*initialization (2)	*/
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);
/*copy (3)	*/
ifstream (const ifstream&) = delete;
/*move (4)	*/
ifstream (ifstream&& x);

在此著重關注第(2)種初始化方式:第一個參數為檔名,第二個參數為檔案開啟模式。

可選的開啟模式包括std::ios_base::openmode的五個型別:inoutbinaryateapptrunc。這些模式可以用bitwise OR operator(|)來進行組合。

check status

參考ifstream: check if opened successfully,為了檢查檔案是否開啟成功,我們可以使用對std::ifsstreamoverload過的!運算子。

close

std::ifstream::close函數的簽名:

void close();

其作用為:

Close file
Closes the file currently associated with the object, disassociating it from the stream.

即關閉檔案,取消它與input stream的關聯。

TensorRT中的例子

TensorRT/parsers/caffe/caffeParser/readProto.h的函數readBinaryProto中。

創建ifstream物件:

std::ifstream stream(file, std::ios::in | std::ios::binary);

注意到這裡使用的std::iosstd::ios_base的子類別。

檢查檔案是否開啟成功:

if (!stream)
{
    RETURN_AND_LOG_ERROR(false, "Could not open file " + std::string(file));
}

關閉檔案:

stream.close();

參考連結

std::ifstream

ifstream: check if opened successfully

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值