Hi there sir.
I just want to ask some help with regarding file handling in c++. I am using bloodshed dev and been stocked with my final project. The problem is a simple inventory system that can append and delete stocks with the text file it is stored. Anyway, I just wanted to have a good samples on appending and deleting text from files and I think I could finish it. I'm not quite sure if this will be read by you or the others so I'll still not post my partial codes here. Kind of shy, you know. :D hope to hear from you soon.
To append data to a text file, open the file for output in append mode.
For example, this will append lines from stdin to "file.txt".
std::ofstream file( "file.txt", std::ios::out|std::ios::app ) ;
std::string str ;
std::cout << "enter lines to be appended to the file. \n"
"enter EOF (ctrl+D in Unix, ctrl+Z in Windows) to quit\n" ;
while( std::getline( std::cin, str ) ) file << str << '\n' ;
To delete lines of text from a file:
1. open the file for input and a temporary file for output
2. read line by line from the file and copy it to the temporary file except for lines to be deleted.
3. close both files.
4. finally copy the temporary file back to the original file
int lime_number = 0 ;
std::cout << "line (zero based; first line is zero) to be deleted? " ;
if( std::cin >> line_number )
std::ifstream file( "file.txt" ) ;
std::ofstream temp( "temp.tmp" ) ;
std::string line ;
for( int cnt = 0 ; std::getline( file, line ) ; ++cnt )
if( cnt != line_number ) temp << line << '\n' ;
std::ifstream temp( "temp.tmp" ) ;
std::ofstream file( "file.txt" ) ;
file << temp.rdbuf() ;