C++ file operation snippets
I always google for these snippets so I decided to put them all in one place; below are some common c++ file operations.
Open a file in binary mode
std::ifstream ifs; ifs.open("test.mov", std::ios::in | std::ios::binary); if(!ifs.is_open()) { printf("Error trying to open the file.\n"); ::exit(EXIT_FAILURE); }
Reading a binary file into an existing std::vector
std::ifstream ifs; ifs.open("test.mov", std::ios::in | std::ios::binary); std::vector<char> buffer; buffer.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>()); ifs.close()
Another variant to read a file into a buffer.
std::ifstream ifs(filepath.c_str(), std::ios::in | std::ios::binary); std::vector<uint8_t> contents(std::istreambuf_iterator<char>(ifs), {});
Reading a text file into a string (note the extra parathesis for std::istreambuf_iterator)
std::ifstream ifs(filepath.c_str(), std::ios::in); if(!ifs.is_open()) { return false; } std::string str( (std::istreambuf_iterator<char>(ifs)) , std::istreambuf_iterator<char>());
Reading a text file using pure C
int read_file(const char* path, char* buf, int len) { /* try to open the file */ FILE* fp = fopen(path, "r"); if(!fp) { printf("Error: cannot read file: %s\n", path); return -1; } /* find size */ long size = 0; fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); if(size > len) { printf("Error: file size it too large for given buffer. We need: %ld bytes.\n", size); fclose(fp); return -2; } size_t r = fread(buf, size, 1, fp); if(r != 1) { printf("Error: cannot read file into buffer.\n"); fclose(fp); return -3; } return (int)size; }
Check the file size
ifs.seekg(0, std::ifstream::end); size_t fsize = ifs.tellg(); printf("File size: %ld.\n", fsize);
Jump to a position
ifs.seekg(1024, std::ios_base::beg); if(!ifs) { printf("Error trying to jump to a position.\n"); ::exit(EXIT_FAILURE); }
Get the curent position
size_t pos = ifs.tellg(); printf("Current position: %ld.\n", pos);
Jump to a absolute position
ifs.seekg(0, std::ios_base::beg);
Read some bytes
const size_t buffer_size = 1024 * 1024 * 10; char* buffer = new char[buffer_size]; size_t read_size = buffer_size; if(fsize < read_size) { read_size = fsize; printf("The file is smaller then the number buffer.\n"); } printf("Reading: %ld\n", read_size); ifs.read(buffer, read_size); if(!ifs) { printf("Error trying to into buffer.\n"); exit(EXIT_FAILURE); } if(ifs.gcount() != sizeof(buffer)) { printf("Number of bytes is not the same as requested.\n"); } printf("Read: %ld bytes into buffer\n", ifs.gcount()); delete[] buffer; buffer = NULL;
Read all bytes
do { ifs.read((char*)buffer, sizeof(buffer)); nread = ifs.gcount(); for (size_t i = 0; i < nread; ++i) { sprintf(hexbuf, "0x%02x", buffer[i]); ofs_source << hexbuf << ", "; ++nchars_written; if (nchars_written >= 16) { ofs_source << "\n "; nchars_written = 0; } } } while (ifs.good());
Write some bytes
std::vector<char> buffer; buffer.push_back('a'); buffer.push_back('b'); buffer.push_back('c'); std::ofstream ofs("myfile.bin", std::ios::bin | std::ios::out); ofs.write(&buffer.front(), buffer.size(); ofs.close()
Write the contents of a std::stringstream to a file
std::ofstream ofs("data.txt", std::ios::out); if(!ofs.is_open()) { return; } std::stringstream ss; ss << "some content."; ofs << ss.rdbuf(); ofs.close();
And the complete source:
Compile with:
g++ main.cpp -g -o out && ./out
Complete source
#include <iostream> #include <fstream> #include <stdio.h> int main() { // open a file in binary mode std::ifstream ifs; ifs.open("test.mov", std::ios::in | std::ios::binary); if(!ifs.is_open()) { printf("Error trying to open the file.\n"); ::exit(EXIT_FAILURE); } // check the file size ifs.seekg(0, std::ifstream::end); size_t fsize = ifs.tellg(); printf("File size: %ld.\n", fsize); // jump to a position from the start of the file ifs.seekg(1024, std::ios_base::beg); if(!ifs) { printf("Error trying to jump to a position.\n"); ::exit(EXIT_FAILURE); } // get current position size_t pos = ifs.tellg(); printf("Current position: %ld.\n", pos); // go back to the beginning of the file. ifs.seekg(0, std::ios_base::beg); // read some bytes const size_t buffer_size = 1024 * 1024 * 10; char* buffer = new char[buffer_size]; size_t read_size = buffer_size; if(fsize < read_size) { read_size = fsize; printf("The file is smaller then the number buffer.\n"); } printf("Reading: %ld\n", read_size); ifs.read(buffer, read_size); if(!ifs) { printf("Error trying to into buffer.\n"); exit(EXIT_FAILURE); } if(ifs.gcount() != sizeof(buffer)) { printf("Number of bytes is not the same as requested.\n"); } printf("Read: %ld bytes into buffer\n", ifs.gcount()); delete[] buffer; buffer = NULL; return 0; }
NAT Types
Building Cabinets
Compiling GStreamer from source on Windows
Debugging CMake Issues
Dual Boot Arch Linux and Windows 10
Mindset Updated Edition, Carol S. Dweck (Book Notes)
How to setup a self-hosted Unifi NVR with Arch Linux
Blender 2.8 How to use Transparent Textures
Compiling FFmpeg with X264 on Windows 10 using MSVC
Blender 2.8 OpenGL Buffer Exporter
Blender 2.8 Baking lightmaps
Blender 2.8 Tips and Tricks
Setting up a Bluetooth Headset on Arch Linux
Compiling x264 on Windows with MSVC
C/C++ Snippets
Reading Chunks from a Buffer
Handy Bash Commands
Building a zero copy parser
Kalman Filter
Saving pixel data using libpng
Compile Apache, PHP and MySQL on Mac 10.10
Fast Pixel Transfers with Pixel Buffer Objects
High Resolution Timer function in C/C++
Rendering text with Pango, Cairo and Freetype
Fast OpenGL blur shader
Spherical Environment Mapping with OpenGL
Using OpenSSL with memory BIOs
Attributeless Vertex Shader with OpenGL
Circular Image Selector
Decoding H264 and YUV420P playback
Fast Fourier Transform
OpenGL Rim Shader
Rendering The Depth Buffer
Delaunay Triangulation
RapidXML
Git Snippets
Basic Shading With OpenGL
Open Source Libraries For Creative Coding
Bouncing particle effect
OpenGL Instanced Rendering
Mapping a texture on a disc
Download HTML page using CURL
Height Field Simulation on GPU
OpenCV
Some notes on OpenGL
Math
Gists to remember
Reverse SSH
Working Set
Consumer + Producer model with libuv
Parsing binary data
C++ file operation snippets
Importance of blur with image gradients
Real-time oil painting with openGL
x264 encoder
Generative helix with openGL
Mini test with vector field
Protractor gesture recognizer
Hair simulation
Some glitch screenshots
Working on video installation
Generative meshes
Converting video/audio using avconv
Auto start terminal app on mac
Export blender object to simple file format