On Wed, 05 Nov 2008 14:48:54 +0100, Michael DOUBEZ wrote:
Quote:
You can also use std::copy with istream_ierator/ostream_iterator.
There is also the usage of rdbuf().
std::istream_iterator is what I wanted to use but I am getting lots of
garbage gets printed along with the file contents. See here is a file
which contains only one word: comp.lang.c++ and see how much garbage is
getting printed. 2nd, is it a god idea to put a for loop in main ?
/* 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.1
*
*/
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <iterator>
int print_file( const char* );
int main(int argc, char* argv[] )
{
if( 1 == argc )
{
std::cerr << "No Input File\n";
exit( EXIT_FAILURE );
}
for( int i = 0; i != argc; ++i )
{
if( print_file( argv[i] ) )
{
std::cerr << "error reading file: "
<< argv[i]
<< std::endl;
}
}
return 0;
}
int print_file( const char* pc )
{
const int read_success = 0;
const int read_failure = 1;
std::ifstream ifile(pc);
if( (!ifile) ) return read_failure;
copy( std::istream_iterator<char>(ifile), std::istream_iterator<char>(),
std::ostream_iterator<char>(std::cout,"") );
// we don't need to close the file because the destructor for ifstream
// will automatically do it.
return read_success;
}
=================== OUTPUT =============================
[arnuld@dune cpp]$ g++4 -ansi -pedantic -Wall -Wextra 07-10_04.cpp
[arnuld@dune cpp]$ ./a.out
No Input File
[arnuld@dune cpp]$ ./a.out test.txt
44Qåtd/lib/ld-linux.so.2GNU
^[[?1;2c
)¼Ãð^[[?1;2cAÂEK<ÊHÍgÝORSÙ2¹XLð÷ Û=p
... LOTS OF GARBAGE SNIPPED.....
Áñÿ
R
ñÿ'À
ºñÿÙ!ñÿ(>ñÿC¹ñÿn}LÅû char_traitsIcEERSt13basic_InitD1Ev@@
^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c[arnuld@dune cpp]$
1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c<1;2c1 ;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;
--
www.lispmachine.wordpress.com
my email is @ the above blog.