A
arnuld
This one works to seem fine. Can I make this program better ?
1) the use of get(ch) function was inspired from Stroustrup 21.5.1, page
number 638.
2) I see, when you create an object of std::ifstream while passing a
pointer to it, it automatically opens the file.
3) If I open a file using std:stream, then I am confused whether it
will open the file for writing or appending ?.
/* Section 7.10: Exercise 4
*
* Write a program that reads arbitrary number of files (whose names are
* given as command-line arguments) and writes them to one after another
* on std::cout.
*
* My view: It feels like UNIX cat
*
* VERSION: 1.0
*
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#include <iterator>
int print_file( char* );
int main(int argc, char* argv[] )
{
if( 1 == argc )
{
std::cerr << "No Input File\n";
exit( EXIT_FAILURE );
}
int file_count = (argc - 1);
int idx = 1;
while( file_count-- )
{
if( print_file( argv[idx] ) )
{
std::cerr << "error reading file: "
<< argv[idx]
<< std::endl;
}
++idx;
}
return 0;
}
int print_file( char* pc )
{
const int read_success = 0;
const int read_failure = 1;
std::ifstream ifile(pc);
if( (!ifile) )
{
ifile.close();
return read_failure;
}
char ch;
while( ifile.get(ch) )
{
std::cout << ch;
}
ifile.close();
return read_success;
}
1) the use of get(ch) function was inspired from Stroustrup 21.5.1, page
number 638.
2) I see, when you create an object of std::ifstream while passing a
pointer to it, it automatically opens the file.
3) If I open a file using std:stream, then I am confused whether it
will open the file for writing or appending ?.
/* Section 7.10: Exercise 4
*
* Write a program that reads arbitrary number of files (whose names are
* given as command-line arguments) and writes them to one after another
* on std::cout.
*
* My view: It feels like UNIX cat
*
* VERSION: 1.0
*
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#include <iterator>
int print_file( char* );
int main(int argc, char* argv[] )
{
if( 1 == argc )
{
std::cerr << "No Input File\n";
exit( EXIT_FAILURE );
}
int file_count = (argc - 1);
int idx = 1;
while( file_count-- )
{
if( print_file( argv[idx] ) )
{
std::cerr << "error reading file: "
<< argv[idx]
<< std::endl;
}
++idx;
}
return 0;
}
int print_file( char* pc )
{
const int read_success = 0;
const int read_failure = 1;
std::ifstream ifile(pc);
if( (!ifile) )
{
ifile.close();
return read_failure;
}
char ch;
while( ifile.get(ch) )
{
std::cout << ch;
}
ifile.close();
return read_success;
}