Skip to content

Instantly share code, notes, and snippets.

@lattice0
Created February 22, 2021 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lattice0/85ac2aaba12a09df383fb6ca42d1ca59 to your computer and use it in GitHub Desktop.
Save lattice0/85ac2aaba12a09df383fb6ca42d1ca59 to your computer and use it in GitHub Desktop.
simple boinary file write tests C++
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
std::fstream f;
std::string filePath = "file.txt";
f.open(filePath, std::ios_base::binary | std::ios_base::out | std::ios_base::in | std::ios_base::trunc );
if (!f.is_open()) {
std::cout << "ERROR, file not open" << std::endl;
return 1;
}
//Write some data to vector
std::vector<char> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//Go to beggining of the file to write
f.seekg(0, std::ios::beg);
f.seekp(0, std::ios::beg);
//Write the vector to file
f.write(v.data(), v.size());
f.flush();
//Lets read so we see that things were written to the file
//Don't know why I've put clear, but won't work without it too
//f.clear();
f.seekg(0, std::ios::beg);
f.seekp(0, std::ios::beg);
auto v2 = std::vector<char>(v.size());
//Read things back to file
f.read(v2.data(), v2.size());
if (f) {
std::cout << "did read everything" << std::endl;
} else {
std::cout << "did read only " << f.gcount() << " bytes" << std::endl;
}
f.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment