Created
June 27, 2012 12:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippet stacks the current time into a file then displays its content by opening only one file pointer.