Chapter Eight: Streams: Big C++ by Cay Horstmann
Chapter Eight: Streams: Big C++ by Cay Horstmann
You can also read and write files stored on your hard disk:
ifstream in_file(“input.txt”);
As your program runs and tries to find this file, it WILL ONLY LOOK IN
THE DIRECTORY (FOLDER) IT IS LOCATED IN!
When you specify the file name as a string literal, and the name
contains backslash characters (as in Windows),
you must supply each backslash twice
to avoid having unintended escape characters in the string.
in_file.close();
You already know how to read and write using files – it is the
same syntax as with cin, which is an istream also.
string name;
double value;
in_file >> name >> value;
in_file.open(filename.c_str());
// Check for failure after opening
if (in_file.fail())
{
cout << “Error opening file: “ <<
filename << endl;
return -1;
}
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Writing to a Stream: Just Like cout <<
ofstream out_file;
out_file.open("output.txt");
if (in_file.fail()) { return -1; }
out_file << name << " " << value << endl;
We will display the top 50% of the names stored in the file.
file stream variable named in.
Associate the input
file stream with a file in.open("in.txt");
The open function associates the input stream with the
disk file in.txt and opens it for reading.
named in.txt.
Define a variable word;
Use word to read the first word string word; in >> word;
Simply use the same input operations with which you are
already familiar. The >> operator reads the next word.
file stream variable named out.
Use the output stream variable
to create a new file out.open("out.txt"); Use the open function to create the desired text file.
named out.txt.
Write a line consisting of the out << "Hello" << endl;
To write to a file, use the << operator and
the endlmanipulator that you have already used with cout.
word Hello to out.txt.
What is the effect of the following statements? (answers shown in tiny font
below)
ifstream in_file;
in_file.open("");
string word = "\n";
in_file >> word;
The statements have no effect.
Because there cannot be a file whose name is the empty string, in_file is set to the “failed” state, and no operations have any effect.
char ch;
int n=0; //for reading an entire int
in_file.get(ch);
}
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Functions in <cctype> (Handy for Lookahead): Table 1
isspace White space (space, tab, newline, and the rarely used carriage
return, form feed, and vertical tab)
string line;
ifstream in_file("myfile.txt");
getline(in_file, line);
char cline[100];
in_file.getline(cline, 99); //the int argument
// is the max number of chars to read
string line;
while( getline(in_file, line)) //reads whole file
{
// Process line
}
To solve the problem, any trailing newline in the input buffer must be
removed before calling getline
There are other alternative remedies for deleting the dangling newline,
including calling in.get() or in.ignore(), but we will leave those
as research exercises for the reader.
Set str to the next line in the input. getline(in, str); The getline function reads the next line from the stream and places it in the string str. The newline is not part of the result.
Set str to the next word in the input. in >> str; The >> operator reads the next word from the stream, removing any whitespace that precedes it.
Set ch to the next character in the in >> ch; Use the >> to get the next character from the stream, skipping any whitespace.
Set ch to the next character in the in.get(ch); Use the get function to get the next character from the stream, even if it is whitespace.
ofstream out_file;
out_file.open("output.txt");
if (out_file.fail())
{ return -1; }
out_file << name << " " << value << endl;
That last setfill(' ') re-sets the fill back to the default
space character.
12.345679 123456789.000000
strm << setprecision(6) << fixed << 12.3456789 << " " << 123456789.0;
----------|----------
Count: 177
----------|----------
strm << "----------|----------\n"
<< left << setw(10) << "Count:"
<< right << setw(11) << 177
<< "----------|----------\n";
For money values, choose fixed format with two digits after the decimal point.
out_file << fixed << setprecision(2);
To get the scientific format: a number with one digit before the decimal point
and an exponent. As with the fixed format, the setprecision denotes the
number of digits after the decimal point. :
out_file << scientific << setprecision(3) << 123.456;
produces
1.235e+02
istringstream strm;
//read string into the istringstream buffer
strm.str("January 24, 1973");
string month;
int day;
string comma;
int year;
strm >> month >> day >> comma >> year;
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Converting a string to a single int or double
string int_to_string(int n)
{
ostringstream strm;
strm << n;
return strm.str();
}
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/**
Decomposes an address into city, state, and zip.
@param address an address such as "Ann Arbor, Michigan 48109"
@return a vector<string> with city, state, and zip, such as
{ "Ann Arbor", "Michigan", "48109" }
*/
vector<string> decompose(string address)
{
istringstream strm;
strm.str(address);
. . .
}
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Topic 5
Yes, the cmd shell program calls the main function of your
program.
The user might type into a command shell window for starting
the program named prog:
prog -v input.dat
argc is 3
argv contains these three C strings:
argv[0]: "prog"
argv[1]: "-v"
argv[2]: "input.dat" Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Command Line Example Program: Encrypting A File
We will use the name caesar for our exe, with 3 command line
arguments:
1. An optional -d flag to indicate decrypt instead of encrypt
2. The input file name
3. The output file name
THUS OUR CODE WILL NOT PROMPT THE USER FOR FILE
NAMES!! It will get them as the C-strings in argv[].
For example,
caesar input.txt encrypt.txt
encrypts the file input.txt with the result in encrypt.txt.
caesar -d encrypt.txt output.txt
decrypts the file encrypt.txt and places the result into output.txt.
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Command Line Program: Encrypting A File, Part 1
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
/**
Encrypts a stream using the Ceasar cipher.
@param in the stream to read from
@param out the stream to write to
@param k the encryption key
*/
void encrypt_file(ifstream& in, ofstream& out, int k)
{
char ch;
while (in.get(ch))
{
out.put(ch + k);
}
} Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Command Line Program: Encrypting A File, Part 2
int main(int argc, char* argv[])
{
int key = 3;
int file_count = 0; // The number of files specified
ifstream in_file;
ofstream out_file;
Consider this task: Read two country data files, worldpop.txt and
worldarea.txt (supplied with the book’s companion code).
Afghanistan 50.56
Akrotiri 127.64
Albania 125.91
Algeria 14.18
American Samoa 288.92
. . .
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
How To: Process Text Files, Step by Step, Part 1
The screen has a cursor to show the user where (s)he is typing.
Binary read/write files have two “cursor” positions:
1. the put position – where the next write will go.
2. the get position – where the next read will be.
fstream strm;
strm.open("img.gif", ios::in | ios::out | ios::binary);
You cannot use the >> operator to read a binary file. Instead,
read a byte by calling get()
The BMP image file format is pretty simple. Other formats such
as PNG, GIF, JPG are far more complex, as they compress
the image to save space.
Pure red is the values: 0 0 255 (no blue, no green, all red)
Medium gray is 128 128 128 (half of 255 for all three)
For example,
if a row consisted of merely three pixels,
one cyan, one red, one medium gray,
there would three padding bytes.
The numbers would be:
255 255 0 0 0 255 128 128 128 x y z
Now that you know all there is to know about BMP files
for 24-bit true color images, we’ll write code to create the
negative of an input image file.
// sec06/imagemod.cpp
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
/**
Processes a pixel by forming the negative.
@param blue the blue value of the pixel
@param green the green value of the pixel
@param red the red value of the pixel
*/
void process(int& blue, int& green, int& red)
{
blue = 255 - blue;
green = 255 - green;
red = 255 - red;
}
Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Program to Produce the Negative, Part 2
/**
Gets an integer from a binary stream.
@param stream the stream
@param offset the offset at which to read the integer
@return the integer starting at the given offset
*/
int get_int(fstream& stream, int offset)
{
stream.seekg(offset);
int result = 0;
int base = 1;
for (int i = 0; i < 4; i++)
{
result = result + stream.get() * base;
base = base * 256;
}
return result;
} Big C++ by Cay Horstmann
Copyright © 2018 by John Wiley & Sons. All rights reserved
Program to Produce the Negative, Part 3
int main()
{
cout << "Please enter the file name: ";
string filename;
cin >> filename;
fstream stream;
char cstring[100];
in_file.getline(cstring, 99);