Выбрать главу

    s.replaceErrors();

    s.saveFiles();

  }

} ///:~

You can replace the marker with one of your choice.

Each file is read a line at a time, and each line is searched for the marker appearing at the head of the line; the line is modified and put into the error line list and into the string stream, edited. When the whole file is processed, it is closed (by reaching the end of a scope), it is reopened as an output file, and edited is poured into the file. Also notice the counter is saved in an external file. The next time this program is invoked, it continues to sequence the counter.

A simple data logger

This example shows an approach you might take to log data to disk and later retrieve it for processing. It is meant to produce a temperature-depth profile of the ocean at various points. To hold the data, a class is used:.

//: C04:DataLogger.h

// Datalogger record layout

#ifndef DATALOG_H

#define DATALOG_H

#include <ctime>

#include <iosfwd>

#include <string>

using std::ostream;

struct Coord {

  int deg, min, sec;

  Coord(int d = 0, int m = 0, int s = 0)

    : deg(d), min(m), sec(s) {}

  std::string toString() const;

};

ostream& operator<<(ostream&, const Coord&);

class DataPoint {

  std::time_t timestamp; // Time & day

  Coord latitude, longitude;

  double depth, temperature;

public:

  DataPoint(std::time_t ts, const Coord& lat,

            const Coord& lon, double dep, double temp)

    : timestamp(ts), latitude(lat), longitude(lon),

      depth(dep), temperature(temp) {}

  DataPoint() : timestamp(0), depth(0), temperature(0) {}

  friend ostream& operator<<(ostream&, const DataPoint&);

};

#endif // DATALOG_H ///:~

A DataPoint consists of a time stamp, which is stored as a time_t value as defined in <ctime>, longitude and latitude coordinates, and values for depth and temperature. We use inserters for easy formatting. Here’s the implementation file:.

//: C04:DataLogger.cpp {O}

// Datapoint implementations

#include "DataLogger.h"

#include <iomanip>

#include <iostream>

#include <sstream>

#include <string>

using namespace std;

ostream& operator<<(ostream& os, const Coord& c) {

  return os << c.deg << '*' << c.min << '\''

            << c.sec << '"';

}

string Coord::toString() const {

  ostringstream os;

  os << *this;

  return os.str();

}

ostream& operator<<(ostream& os, const DataPoint& d) {

  os.setf(ios::fixed, ios::floatfield);

  char fillc = os.fill('0'); // Pad on left with '0'

  tm* tdata = localtime(&d.timestamp);

  os << setw(2) << tdata->tm_mon + 1 << '\\'

     << setw(2) << tdata->tm_mday << '\\'

     << setw(2) << tdata->tm_year+1900 << ' '

     << setw(2) << tdata->tm_hour << ':'

     << setw(2) << tdata->tm_min << ':'

     << setw(2) << tdata->tm_sec;

  os.fill(' '); // Pad on left with ' '

  streamsize prec = os.precision(4);

  os << " Lat:" << setw(9) << d.latitude.toString()

     << ", Long:" << setw(9) << d.longitude.toString()

     << ", depth:" << setw(9) << d.depth

     << ", temp:" << setw(9) << d.temperature;

  os.fill(fillc);

  os.precision(prec);

  return os;

} ///:~

The Coord::toString( ) function is necessary because the DataPoint inserter calls setw( ) before it prints the latitude and longitude. If we used the stream inserter for Coord instead, the width would only apply to the first insertion (that is, to Coord::deg), since width changes are always reset immediately. The call to setf( ) causes the floating-point output to be fixed-precision, and precision( ) sets the number of decimal places to four. Notice how we restore the fill character and precision to whatever they were before the inserter was called.

To get the values from the time encoding stored in DataPoint::timestamp, we call the function std::localtime( ), which returns a static pointer to a tm object. The tm struct has the following layout:

struct tm {

  int tm_sec; // 0-59 seconds

  int tm_min; // 0-59 minutes

  int tm_hour; // 0-23 hours

  int tm_mday; // Day of month

  int tm_mon; // 0-11 months

  int tm_year; // Years since 1900

  int tm_wday; // Sunday == 0, etc.

  int tm_yday; // 0-365 day of year

  int tm_isdst; // Daylight savings?

};

Generating test data

Here’s a program that creates a file of test data in binary form (using write( )) and a second file in ASCII form using the DataPoint inserter. You can also print it out to the screen, but it’s easier to inspect in file form.

//: C04:Datagen.cpp

// Test data generator

//{L} DataLogger

#include <cstdlib>

#include <cstring>

#include <fstream>

#include "../require.h"

#include "DataLogger.h"

using namespace std;

int main() {

  ofstream data("data.txt");

  assure(data, "data.txt");

  ofstream bindata("data.bin", ios::binary);

  assure(bindata, "data.bin");

  time_t timer;

  Coord lat(45,20,31);

  Coord lon(22,34,18);

  // Seed random number generator:

  srand(time(&timer));

  for(int i = 0; i < 100; i++, timer += 55) {

    // Zero to 199 meters:

    double newdepth  = rand() % 200;

    double fraction = rand() % 100 + 1;

    newdepth += 1.0 / fraction;

    double newtemp = 150 + rand()%200; // Kelvin

    fraction = rand() % 100 + 1;

    newtemp += 1.0 / fraction;

    const DataPoint d(timer, Coord(45,20,31),

       Coord(22,34,18), newdepth,

       newtemp);

    data << d << endl;