DataReelDataReelC++ Transition Guide

Examples › General Examples

general_device_cache

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_general/device_cache/testprog.cpp · Modern: examples_modern/general/device_cache/modern.cpp

Modern equivalent of the device cache test, which copies a file through gxDeviceBucketCache buckets. The standard library buffers streams itself, so a copy is std::filesystem::copy_file() (which can use the operating system's fast copy), or, when the data has to pass through the program, a read/write loop over a std::vector<char> buffer. Writing "out << in.rdbuf()" copies a whole stream in one statement. Each method is timed with std::chrono::steady_clock.

Usage: modern infile outfile (with no arguments the program makes a 1 MB test file).

Legacy calls in this program

LegacyModern C++StandardNotes
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98
gxDeviceCache, gxDeviceBucketCachestreams buffer themselves: std::filesystem::copy_file(), out << in.rdbuf()C++17

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/device_cache/testprog.cpp 191 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include <sys/types.h>
#include <sys/stat.h>
#include "dfileb.h"
#include "devcache.h"
#include "memblock.h"
#include "membuf.h"

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

// Example class used to create the device cache
class gxFileCache : public gxDeviceCache
{
public:
  gxFileCache(unsigned CacheSize = 1024);
  ~gxFileCache() { }

public:
  void Flush() { cache.Flush(); } // Flush the cache buckets
  unsigned BucketsInUse() { return cache.BucketsInUse(); }
  void CloseOutputFile() { infile.df_Close(); }
  void CloseInputFile() { outfile.df_Close(); }
  int OpenInputFile(const char *in);
  int OpenOutputFile(const char *out);
  unsigned LoadFile(gxDeviceCachePtr p);
  int CopyFileToFile(const char *in, const char *out, int *bc = 0);

private: // Base class interface
  void Read(void *buf, unsigned Bytes, gxDeviceTypes dev);
  void Write(const void *buf, unsigned Bytes, gxDeviceTypes dev);

private: // Device objects
  DiskFileB outfile; // File used to output data
  DiskFileB infile;  // File used to input data
  
private: // Device cache
  gxDeviceBucketCache cache;

public: // Functions used to get the current device cache
  gxDeviceBucketCache *GetCache() { return &cache; }
};

gxFileCache::gxFileCache(unsigned CacheSize) : cache(CacheSize) 
{ 
  ready_for_writing = 1; 
  ready_for_reading = 1;
  cache.Connect(this); 
}

void gxFileCache::Read(void *buf, unsigned Bytes, gxDeviceTypes dev) 
{
  switch(dev) {
    case gxDEVICE_DISK_FILE:
      if(!infile) { ready_for_reading = 0; return; }
      else { ready_for_reading = 1; }
      infile.df_Read((char *)buf, Bytes);
      break;

    default:
      break;
  }
}
  
void gxFileCache::Write(const void *buf, unsigned Bytes, gxDeviceTypes dev) 
{
  switch(dev) {
    case gxDEVICE_CONSOLE:
      cout.write((char *)buf, Bytes);
      break;

    case gxDEVICE_DISK_FILE:
      if(!outfile) { ready_for_writing = 0; return; }
      else { ready_for_writing = 1; }
      outfile.df_Write((char *)buf, Bytes);
      break;
      
    default:
      break;
  }
}

int gxFileCache::CopyFileToFile(const char *in, const char *out, int *bc)
{
  if(!OpenInputFile(in)) return 0;
  if(!OpenOutputFile(out)) return 0;

  if(!cache) return 0;
  
  gxDeviceTypes o_device = gxDEVICE_DISK_FILE; // Output device
  gxDeviceTypes i_device = gxDEVICE_NULL;      // No input buffering

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 
  *bc = LoadFile(p); // Load the file into the cache 
  cache.Flush(); // Ensure all the buckets a written to the output device
  infile.df_Close();
  outfile.df_Close();
  return 1;
}

unsigned gxFileCache::LoadFile(gxDeviceCachePtr p)
// Load a file from disk into the device cache. Returns the
// number bytes read from the file.
{
  unsigned byte_count = 0;
  char sbuf[MEMORY_BLOCK_SIZE];

  infile.df_Rewind();

  while(!infile.df_EOF()) {
    if(infile.df_Read(sbuf, MEMORY_BLOCK_SIZE) != DiskFileB::df_NO_ERROR) {
      if(infile.df_GetError() != DiskFileB::df_EOF_ERROR) {
	break;
      }
    }
    p->Load(sbuf, infile.df_gcount());
    byte_count += infile.df_gcount();
  }

  return  byte_count;
}

int gxFileCache::OpenInputFile(const char *in)
// Open the file if it exists. Returns false
// it the file cannot be opened or if it does
// not exist.
{
  infile.df_Open(in);
  if(!infile) return 0;
  return 1;
}

int gxFileCache::OpenOutputFile(const char *out)
// Open the specified file for writing and truncate
// it. Returns false if the file cannot be opened.
{
  outfile.df_Create(out);
  if(!outfile) return 0;
  return 1;
}

int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  if(argc < 3) {
    cout << "\n";
    cout << "Usage: " << argv[0] << " infile outfile" << "\n";
    cout << "\n";
    return 0;
  }

  char *in = argv[1];
  char *out = argv[2];

  int cache_size = 1024;
  gxFileCache dev(cache_size); // Device cache used to process a file

  cout << "Creating a device cache using " << cache_size 
       << " cache buckets." << "\n";
  cout << "Reserving " << (sizeof(gxDeviceBucket) * cache_size) 
       << " bytes of memory." << "\n";

  int byte_count;
  
  if(!dev.CopyFileToFile(in, out, &byte_count)) {
    cout << "Error copying file." << "\n";
    return 0;
  }

  cout << "Finished processing file." << "\n";
  cout << "Byte count = " << byte_count << "\n";

  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/device_cache/modern.cpp 69 lines
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace fs = std::filesystem;
using clock_type = std::chrono::steady_clock;

long long ms_since(clock_type::time_point t)
{
  return std::chrono::duration_cast<std::chrono::microseconds>(
    clock_type::now() - t).count();
}

std::uintmax_t copy_with_buffer(const fs::path &in, const fs::path &out)
{
  std::ifstream src(in, std::ios::binary);
  std::ofstream dst(out, std::ios::binary | std::ios::trunc);
  std::vector<char> bucket(64 * 1024);  // One cache "bucket"
  std::uintmax_t bytes = 0;
  while(src.read(bucket.data(), std::streamsize(bucket.size())) || src.gcount()) {
    dst.write(bucket.data(), src.gcount());
    bytes += std::uintmax_t(src.gcount());
  }
  return bytes;
}

int main(int argc, char **argv)
{
  fs::path in = argc > 2 ? argv[1] : "devcache_test.in";
  fs::path out = argc > 2 ? argv[2] : "devcache_test.out";
  bool made = false;
  if(argc <= 2) {
    std::ofstream f(in, std::ios::binary);
    for(int i = 0; i < 1024 * 1024; i++) f.put(char('A' + i % 26));
    made = true;
  }
  if(!fs::exists(in)) { std::cout << "Cannot open " << in << "\n"; return 1; }

  auto t = clock_type::now();
  auto bytes = copy_with_buffer(in, out);
  std::cout << "Buffered copy: " << bytes << " bytes in " << ms_since(t)
            << " us\n";

  t = clock_type::now();
  {
    std::ifstream src(in, std::ios::binary);
    std::ofstream dst(out, std::ios::binary | std::ios::trunc);
    dst << src.rdbuf();
  }
  std::cout << "rdbuf() copy:  " << fs::file_size(out) << " bytes in "
            << ms_since(t) << " us\n";

  t = clock_type::now();
  fs::copy_file(in, out, fs::copy_options::overwrite_existing);
  std::cout << "copy_file():   " << fs::file_size(out) << " bytes in "
            << ms_since(t) << " us\n";

  bool same = fs::file_size(in) == fs::file_size(out);
  std::cout << (same ? "The copies match in size\n" : "Size mismatch\n");
  if(made) { fs::remove(in); fs::remove(out); }
  return same ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target general_device_cache
./build-modern/general_device_cache
# or without CMake:
g++ -std=c++17 -pthread -o general_device_cache examples_modern/general/device_cache/modern.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Buffered copy: 1048576 bytes in 338 us
rdbuf() copy:  1048576 bytes in 1425 us
copy_file():   1048576 bytes in 40867 us
The copies match in size