Fork me on GitHub

Project Notes

#219 Files

Simple binary file operations with C++.

Notes

Binary Output file streams

Open ofstream in binary mode:

ofstream output;
output.open("filename", ios::binary);

Write as a char stream into struct:

Person person = {...};
output.write(reinterpret_cast<char *>(&person), sizeof(Person));

Binary Input file streams

Open ifstream in binary mode:

ifstream input;
input.open("filename", ios::binary);

Read as a char stream into struct:

Person person;
input.read(reinterpret_cast<char *>(&person), sizeof(Person));

Structure-Packing

Use Structure-Packing Pragmas to force byte alignment e.g.

#pragma pack(push, 1)
struct Person {
  char name[50];
  int age;
  double height;
};
#pragma pack(pop)

Running the Example

$ make
c++ -std=c++17 -Wall -O3    example_1a_write.cpp   -o example_1a_write
c++ -std=c++17 -Wall -O3    example_1b_read.cpp   -o example_1b_read
./example_1a_write; ./example_1b_read;
Writing Person to data.bin..
Reading Person from data.bin..
Joey: 42: 1.7

Credits and References

About LCK#219 C++
Project Source on GitHub Return to the Project Catalog

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.

LittleArduinoProjects LittleModelArt More on my blog