473,624 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2472
On Wed, 05 Nov 2008 14:48:54 +0100, Michael DOUBEZ wrote:

You can also use std::copy with istream_ierator/ostream_iterato r.
There is also the usage of rdbuf().

std::istream_it erator 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_it erator<char>(if ile), std::istream_it erator<char>(),
std::ostream_it erator<char>(st d::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_traitsIcEE RSt13basic_Init D1Ev@@
^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c^[[?1;2c[arnuld@dune cpp]$
1;2c1;2c1;2c1;2 c1;2c1;2c1;2c1; 2c1;2c1;2c1;2c< 1;2c1;2c1;2c1;2 c1;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_iterato r.
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_it erator<std::str ing>(ifile), std::istream_it erator<std::str ing>(),
std::ostream_it erator<std::str ing>(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_ter ator<char>(ifil e)

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_iterato r ?

--
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(st d::ios_base::sk ipws);
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_it erator 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
3136
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 had done myself a disservice by having not attempted and completed the exercises. I intend to rectify that. My current routine is to read a chapter and then attempt every exercise problem, and I find that this process is leading to a greater...
7
2344
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? which calls cause the compiler to to introduce a temporary variable? solution: this is the code ----------------------------------------------------------- #include <iostream> void f(char) {};
5
2225
by: arnuld | last post by:
this is the code: ------------------------------------------------------------------ #include <iostream> void g(char&){}; void h(const char&) {}; int main() { char c;
6
1754
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 year & the number of days in each month. write out that table. do this using: "a struct & an array of that struct" this is the solution i have created: #include <iostream>
0
1746
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 opposite as an exercise which is writing it as a "declaration without definition". please check whether i am right or wrong:
2
5331
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 -------------- /* Stroustrup 3e, section 4.11, exercise 5 STATEMENT:
6
3037
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 table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice:
14
2464
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: Read a sequence of words from the input. use "quit" as the word
27
2436
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 STATEMENT: Read a sequence of words from the input. use "quit" as the word to terminate the input. Print the words in the order they were entered. don't print a word twice.modify the programme to sort the
0
8179
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8685
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8493
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6112
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4084
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2613
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1493
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.