473,395 Members | 1,583 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Stroustrup Section 7.10, Exercise 4

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::ostream, 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;
}

--
www.lispmachine.wordpress.com
my email is @ the above blog.
Google Groups is UnBlocked now :)
Nov 5 '08 #1
6 2456
On Wed, 05 Nov 2008 14:48:54 +0100, Michael DOUBEZ wrote:

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.
Nov 6 '08 #2
On Wed, 05 Nov 2008 14:48:54 +0100, Michael DOUBEZ wrote:
You can also use std::copy with istream_ierator/ostream_iterator.
There is also the usage of rdbuf().
Here is what I am getting:

/* 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.2
*
*/

#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 = 1; i <= argc; ++i )
{
if( print_file( argv[i] ) )
{
std::cerr << "\n\n-------------------error reading file: "
<< argv[i]
<< " --------------------------------\n"
<< 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<std::string>(ifile), std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(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 test.txt
-------------------error reading file: comp.alng.c++ [arnuld@dune cpp]$
Why it is printing error reading file always ?
2nd, even if it is printing the error by some program mistake then why
it not full error, why only half error message ?

--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 6 '08 #3
On Thu, 06 Nov 2008 12:34:06 +0500, arnuld wrote:

for( int i = 1; i <= argc; ++i )
This is the source of my all frustration. It should be < not <= :-\ . I
still have one question , using:

std::stream_terator<char>(ifile)

kills the formatting of the output. I mean the original file and output
are different in formatting but with:

while( ifile.get(ch) ) std::cout << ch;

the formatting remains the same. How can I keep formatting same with
istream_iterator ?

--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 6 '08 #4
On Thu, 06 Nov 2008 09:08:07 +0100, Michael DOUBEZ wrote:

You need to read the white spaces; insert the following before copying:
ifile.unsetf(std::ios_base::skipws);
skipws means skip the white space (or don't read it) but you say with it
it will read the white space. So I am little confused and what unsetf is ?

Program is working fine though.
--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 6 '08 #5
On Thu, 06 Nov 2008 09:38:50 +0100, Michael DOUBEZ wrote:

Yes but you unset it; unsetf remove the format flags specified in
parameters. In this case, it will remove the flag telling the stream to
skip whitespaces.
okay . I understand it now :)

It is equivalent to:
char c;
ifile>>noskiws>>c;

Just a question. Why std::istream_iterator is created with an intention to
skip whitespace . Some specific reason ?


--
www.lispmachine.wordpress.com
my email is @ the above blog.
Nov 6 '08 #6
On 2008-11-05 12:48, arnuld wrote:
This one works to seem fine. Can I make this program better ?
int print_file( char* pc )
{
const int read_success = 0;
const int read_failure = 1;
I would declare those constants outside the function so that whoever
calls print_file can use them to test for success or not:

if( read_success == print_file( argv[idx] ) )

--
Erik Wikström
Nov 8 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Oplec | last post by:
Hi, I am learning standard C++ as a hobby. The C++ Programming Language : Special Edition has been the principal source for my information. I read the entirety of the book and concluded that I...
7
by: arnuld | last post by:
problem: define functions F(char), g(char&) & h(const char&). call them with arguments 'a', 49, 3300, c, uc & sc where c is a char, uc is unsigned char & sc is signed char. whihc calls are legal?...
5
by: arnuld | last post by:
this is the code: ------------------------------------------------------------------ #include <iostream> void g(char&){}; void h(const char&) {}; int main() { char c;
6
by: arnuld | last post by:
i do not have any problem here. i solved the problem but i wanted to know the views of you. please look at it from a newbie's perspective: problem: define a table with names of months of the...
0
by: arnuld | last post by:
Stroustrup has a table in section 4.9 of declarations and definitions. he asks to write a similar table but in opposite sense: char ch; // declaration with definition he asks to do the...
2
by: arnuld | last post by:
MAX and MIN values of CHAR could not be displayed. Why ? BTW, any advice on improvement ? (please remember i have covered chapter 4 only) ------------- PROGRAMME -------------- /*...
6
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a...
14
by: arnuld | last post by:
there is no "compile-time error". after i enter input and hit ENTER i get a run-time error. here is the code: ---------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 11 STATEMENT:...
27
by: arnuld | last post by:
it works fine without any trouble. i want to have advice on improving the code from any angle like readability, maintenance etc: ---------- PROGRAMME ------------ /* Stroustrup, 5.9, exercise 11...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.