C++/writing at specific locations in a .txt file using c++
Expert: vijayan - 5/13/2009
QuestionDear sir,
I have a text file(.txt), it contains 10000 lines (decimal values with + and -) continous of fixed length.
My aim is to create a black line (break) at every 100 lines in the text file, using c++. Is it possible?
This is my first task after that work continues ...
If possible, please help me in programming easier & quicker way to tackle this problem.
AnswerThe simplest way to do this is:
a. read the original file line by line
b. write out each line read into a second file.
c. when 100 lines have been written, write an additional new line into the second file.
finally, delete the original file and rename the second file as the original file.
#include <fstream>
#include <string>
int main()
{
const char* input_file_name = "whatever.txt" ;
const char* output_file_name = "whatever.with_breaks.txt" ;
enum { NLINES_TO_INSERT_BREAK = 100 } ;
std::ifstream fin( input_file_name ) ;
std::ofstream fout( output_file_name ) ;
std::string line ;
int cnt_lines = 0 ;
while( std::getline( fin, line ) )
{
fout << line << '\n' ;
if( ( ++cnt_lines % NLINES_TO_INSERT_BREAK ) == 0 ) fout << '\n' ;
}
}