Back to posts.

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;
}