[英]Reading and Writing to a Binary File in C++
我有 2 個變量,字符串和 integer,我想將這兩個數據寫入二進制文件。 我在 google 上搜索過,其中一些正在使用 memcpy、fstream 等。 但是,我發現的只是一種存儲具有相同數據類型的數據的方法,例如僅 integer 或僅字符串。 我想將字符串和 integer 數據類型存儲在一個二進制文件中,並且我沒有在結構中聲明變量。
我如何在 C++ 中做到這一點?
使用fstream
是最簡單的方法:
#include <fstream>
#include <string>
int main()
{
int number = 3;
std::string str = "my_str";
// Writing
std::fstream out("file", std::ios::binary | std::ios::out);
out << number << str;
// We are going to open the file again, so we need to close it first
// We could have opened a new scope instead
out.close();
// Reading
std::fstream in("file", std::ios::binary | std::ios::in);
in >> number >> str;
// No need to close the file, it is done thanks to RAII
}
但是,您需要知道 object 表示不保證相同,具體取決於操作系統、編譯器......
如果您將它與相同的編譯器、相同的版本和相同的操作系統一起使用,這保證可以工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.