Skip to content

Instantly share code, notes, and snippets.

@duckie
Created June 27, 2012 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duckie/3003899 to your computer and use it in GitHub Desktop.
Save duckie/3003899 to your computer and use it in GitHub Desktop.
C++ : How to write and read with only one file open for both operations
#include <iostream>
#include <iomanip>
#include <ctime>
#include <fstream>
#include <string>
std::ostream & format_2_l0(std::ostream & iStream)
{
return iStream << std::setw(2) << std::setfill('0');
}
int main(int argc, char* argv[])
{
std::string my_file("file.txt");
std::fstream file_p(my_file.c_str(), std::ios::in | std::ios::app); // <- Pour ajouter à la fin du contenu
// std::fstream file_out(my_file, std::ios::in | std::ios::out); // <- Pour écraser le contenu
if(file_p)
{
// Ecrire
std::time_t now = std::time(0);
std::tm * tm_now = std::localtime(&now);
format_2_l0(file_p) << tm_now->tm_hour << "h";
format_2_l0(file_p) << tm_now->tm_min << " ";
format_2_l0(file_p) << tm_now->tm_sec << "s";
file_p << std::endl;
// Lire
std::string ligne;
file_p.seekg(0,std::ios::beg);
while ( std::getline( file_p, ligne ) )
std::cout << ligne << std::endl;
file_p.close();
}
return 0;
}
@duckie
Copy link
Author

duckie commented Jun 27, 2012

This snippet stacks the current time into a file then displays its content by opening only one file pointer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment