twirl, you need to be more specific:
1. What is the format on the output?
2. Are the contents to be written out to the file again (overwriting the file or to a new file)?
3. Is there supposed to be some way out of the infinite loop from your step 4?
I feel that I am misunderstanding your requirements, but this is what I have:
Code:
#include <iostream>
#include <vector>
#include <fstream>
#include <ctime>
#include <string>
#include <iomanip>
int random_line( const char *filename );
int main( int argc, char **argv )
{
if( argc != 2 )
std::cout << "Usage: " << argv[0] << " <filename>" << std::endl;
else
random_line( argv[1] );
return 0;
}
int random_line( const char *filename )
{
// Produce a random line continuously.
std::ifstream fptr( filename, std::ios::in );
std::vector< std::string > positions;
std::vector< std::string >::size_type line;
std::string buffer;
// Read the contents in.
while( getline( fptr, buffer, '\n' ) )
positions.push_back( buffer );
// Explicit close.
fptr.close();
// Forever print a random line from the source file in the format of
// <line number> = <line>
for( srand( unsigned( time( 0 ) ) ); ; )
line = static_cast< std::vector< std::string >::size_type >( ( double( rand() ) / RAND_MAX ) * positions.size() ),
std::cout << std::setw( 12 ) << line << " = " << positions[ line ].c_str() << std::endl;
// Never reaches here.
return 0;
}
And running with itself as an argument.
Code:
tcsh_prompt>g++ random_line.cpp && a.out random_line.cpp | head -20
38 = std::cout << std::setw( 12 ) << line << " = " << positions[ line ].c_str() << std::endl;
39 =
36 = for( srand( unsigned( time( 0 ) ) ); ; )
17 = }
17 = }
8 =
11 = if( argc != 2 )
30 =
24 = std::vector< std::string >::size_type line;
30 =
1 = #include <vector>
15 =
28 = while( getline( fptr, buffer, '\n' ) )
31 = // Explicit close.
4 = #include <string>
3 = #include <ctime>
29 = positions.push_back( buffer );
21 = // Produce a random line continuously.
9 = int main( int argc, char **argv )
3 = #include <ctime>