www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1995/02/27/02:49:11

Date: Mon, 27 Feb 1995 03:18:06 -0400 (AST)
From: Bill Davidson <bdavidson AT ra DOT isisnet DOT com>
Subject: Problems with simple fstream program
To: djgpp AT sun DOT soe DOT clarkson DOT edu

Hi all:

Sorry if this is inappropriate, but I have been trying to teach myself 
C++ (I've been programming in C for a few years now) using a tutorial 
package from Simtel (came highly regarded) and djgpp.  I was disappointed 
when one of the "baby" demo programs from chapter one (!) did not behave 
as expected.  What I want to know is, is this a problem with the 
tutorial, or is this a program that should work?  And if the latter, why 
doesn't it?

The program prompts the user for an input file (I used the program's 
source file, fstream.cpp), then copies it to another file called "copy" 
and to the printer.  Here's the code:
-----------------------------------
#include <iostream.h>
#include <fstream.h>
#include <process.h>

void main () {

ifstream infile;
ofstream outfile;
ofstream printer;
char filename[20];

cout << "Enter the desired file to copy ----> ";
cin >> filename;

infile.open (filename, ios::nocreate);
if (!infile) {
    cout << "Input file cannot be opened.\n";
    exit (1);
}

outfile.open ("copy");
if (!outfile) {
    cout << "Output file cannot be opened.\n";
    exit (1);
}

printer.open ("PRN");
if (!printer) {
    cout << "There is a problem with the printer.\n";
    exit (1);
}

char one_char;
printer << "This is the beginning of the printed copy.\n\n";

while (infile.get (one_char)) {
    outfile.put (one_char);
    printer.put (one_char);
}

printer << "\n\nThis is the end of the printed copy.\n";

infile.close();
outfile.close();
printer.close();

}

The problem is in the while loop; the expression infile.get(one_char) 
always evaluates to zero.  Is this expected behaviour?  The program 
compiles and runs OK but "copy" is 0 bytes and the printed output is just 
the lines fed via <<.  I don't understand enough about C++ declarations 
(yet) to know thether infile.get() should return a value, so the header 
wasn't much use to me.

Help!
thanx
Bill Davidson
bdavidson AT ra DOT isisnet DOT com


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019