Sunday, 15 July 2012

c++ - How to read time from a file without converting -



c++ - How to read time from a file without converting -

my question general, explain using specific example.

suppose need communicate time between 2 applications. simple way have 1 application write output of gettimeofday() (tv_sec , tv_usec) file , allow other app read it. sec app needs 'convert' strings in order instance of timeval.

is there way avoid conversion?

is there improve way simple file write/read?

assuming both processes on same machine (or @ to the lowest degree on machines of same architecture), results of std::time() (from <ctime>) seconds since epoch, , not need conversion:

std::time_t seconds_since_epoch = std::time(null);

disclaimer: not best method of ipc , need to lock file reading while beingness written, etc. answering question.

update, next comment.

if need write timeval, perhaps easiest way define << , >> operators timeval , write , read these text file (no need worry byte-ordering) as-is (with no conversion):

std::ostream& operator <<(std::ostream& out, timeval const& tv) { homecoming out << tv.tv_sec << " " << tv.tv_usec; } std::istream& operator >>(std::istream& is, timeval& tv) { homecoming >> tv.tv_sec >> tv.tv_usec; }

this allow next (ignoring concurrency):

// author { timeval tv; gettimeofday(&tv, null); std::ofstream timefile(filename, std::ofstream::trunc); timefile << tv << std::endl; } // reader { timeval tv; std::ifstream timefile(filename); timefile >> tv; }

if both process running concurrently, you'll need lock file. here's illustration using boost:

// author { timeval tv; gettimeofday(&tv, null); file_lock lock(filename); scoped_lock<file_lock> lock_the_file(lock); std::ofstream timefile(filename, std::ofstream::trunc); timefile << tv << std::endl; timefile.flush(); } // reader { timeval tv; file_lock lock(filename); sharable_lock<file_lock> lock_the_file(lock); std::ifstream timefile(filename); timefile >> tv; std::cout << tv << std::endl; }

...i've omitted exception handling (when file not exist) clarity; you'd need add together production-worthy code.

c++ file-io ipc

No comments:

Post a Comment