如何将整数向量存储到磁盘,并从C++中保存的文件中读取整数



我在一个向量中有整数,我想将其存储在一个文件中。我不确定我是否保存了它,希望能够从文件中读取整数。

我的尝试。它打印出我存储的第二个整数88。

#include <fstream>
#include <iterator>
#include <string>

class ValueGet {
public:
int data;
ValueGet() {
data = 0;
}
};
int main() {

int first_int = 47;
int second_int = 88;
std::vector<int> int_vec;
int_vec.push_back(first_int);
int_vec.push_back(second_int);
std::ofstream outfile("int_outfile.txt", std::ofstream::binary);
outfile.write(reinterpret_cast<const char*>(int_vec.data() /* or &v[0] pre-C++11 */), sizeof(int) * int_vec.size());
outfile.close();
ValueGet vg;
std::ifstream file;
file.open("int_outfile.txt", std::fstream::binary | std::fstream::out); // Opens a file in binary mode for input operations i.e., getting data from file.
if (!file)
std::cout << "File Not Found.";
else {
file.seekg(0); // To make sure that the data is read from the starting position of the file.
// while (file.read((char *)&vg, sizeof(vg))) // Iterates through the file till the pointer reads the last line of the file.
while (file.read((char*)&vg, sizeof(vg)));
std::cout << "Did it load? " << vg.data;
}
}
outfile.write(reinterpret_cast<const char*>(int_vec /* or &v[0] pre-C++11 */), sizeof(int) * vec_of_vec_of_tensor.size());

应该是

outfile.write(reinterpret_cast<const char*>(int_vec.data() /* or &v[0] pre-C++11 */), sizeof(int) * int_vec.size());

由于ValueGet在上面的代码中是未定义的,我不知道如何建议回读数据。但是,如果要读回矢量,则必须确保矢量大小正确,并再次使用data方法直接读取矢量的数据。

CCD_ 3在上述代码中是不必要的。

最新更新