Created
February 22, 2021 20:24
-
-
Save lattice0/85ac2aaba12a09df383fb6ca42d1ca59 to your computer and use it in GitHub Desktop.
simple boinary file write tests C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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