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
的五個型別:in
,out
,binary
,ate
,app
,trunc
。這些模式可以用bitwise OR operator(|
)來進行組合。
check status
參考ifstream: check if opened successfully,為了檢查檔案是否開啟成功,我們可以使用對std::ifsstream
overload過的!
運算子。
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::ios
為std::ios_base
的子類別。
檢查檔案是否開啟成功:
if (!stream)
{
RETURN_AND_LOG_ERROR(false, "Could not open file " + std::string(file));
}
關閉檔案:
stream.close();