Welcome to Lesson 20!By the end of today's class, you should know...
Announcements
Call-By-Reference Details
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; void swap(int var1, int var2); int main() { int num1 = 0, num2 = 0; cout << "Enter two integers: "; cin >> num1 >> num2; swap(num1, num2); cout << "After calling function: " << num1 << " " << num2 << endl; return 0; } void swap(int var1, int var2) { int temp = var1; var1 = var2; var2 = temp; } |
Enter two integers: 1 2 After calling function: 1 2
Notice that num1
and num2
have the same values before and after calling the function swap()
. Any value assigned to var1
and var2
have no effect on num1
and num2
.
The ampersands tell C++ to use call-by-reference when passing parameter values.
Enter two integers: 1 2 After calling function: 2 1
Notice that num1
and num2
have different values before and after calling the function swap()
. Any value assigned to var1
and var2
change num1
and num2
respectively.
Program I/O
- Program I/O = Program Input/Output
- Input to and output from programs
- Input can be from a keyboard, mouse or file
- Output can be to a display screen, printer or file
- Note that files can be both input and output devices for programs
- Advantages of file I/O:
- Data still exists after the program ends
- Input can be automated (rather than entered manually)
- Output from one program can be input to another
- To store and retrieve data in a file, we need two constructs:
- A file
- A file stream object
- We will look at files first
Files
File: a collection of data stored under a common name on a storage medium.
- Files provide long-term storage of large amounts of data
- Usually, you store files on durable storage mediums
- Magnetic disks
- Optical disks
- Flash storage, like USB storage devices
- Files are a single sequence of bytes
Byte 0 Byte 1 Byte 2 ... Byte n−1 End-of-file marker
- Since the data arranged as bytes, any type of data can be stored in a file
- The operating system keeps track of the number of bytes in a file
- Files must have a name
- Naming requirements depend on the underlying operating system (OS)
- The operating system organizes files into directories
Types of Files
- All data in a file is ultimately just zeros and ones
- Each binary digit can have one of two values: 0 or 1
- A bit is one binary digit
- A byte is a group of eight bits
- These binary digits may represent integer values or text characters
- It is up to the program using the file to understand the meaning and internal format of the data
- In general, programs interpret data using two broad categories: text and binary
Text Files
- In text files, the bits represent printable characters
- Files are usually stored as one byte per character (ASCII)
- Each line is delimited by end-of-line characters:
- Macintosh (before OS-X): "
\r
" - Unix: "
\n
" - Windows: "
\r\n
"
- Macintosh (before OS-X): "
- An example of a text file is source code
- We can read text files because each byte is interpreted by a program as textual characters
- Some of these programs, like TextPad, then display the textual data to your computer's screen
- Since there are many programs that read and display text, text files are called human readable
Binary Files
- Data other than text is usually referred to as binary data
- Each bit represents some type of encoded information
- Such as program instructions or integer data
- Binary files are easily read by the computer but not by humans
- The following table compares binary and text values saved in a file
- First we consider the value "1234" as ASCII codes and compare these bits to a binary value of
1234
- As we can see, the bit patterns are different for the same data when stored as text or binary
Comparing Binary and Textual Data
Description | Byte 0 | Byte 1 | Byte 2 | Byte 3 |
---|---|---|---|---|
"1234" as char 's |
'1' | '2' | '3' | '4' |
"1234" as ASCII codes (bytes) | 49 | 50 | 51 | 52 |
"1234" as ASCII codes (bits) | 00110001 | 00110010 | 00110011 | 00110100 |
(int) 1234 as binary bits |
00000000 | 00000000 | 00000100 | 11010010 |
Streams
Stream: a one-way transmission path that either delivers data to a destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)
- A stream connects a program to an I/O object
- Input stream: an object that provides a sequence of bytes to a program
cin
andcout
are input and output streams
File Streams
File stream: a one-way transmission path used to connect a program to a file.
- File streams can be either input or output streams
- File input streams receive data from a file
- File output streams send data to a file
- File I/O uses streams of type
ifstream
andofstream
- To declare a file input stream, we write code like:
ifstream fin; //declares a file input stream
- Similarly, to declare a file input stream we write code like:
ofstream fout; //declares a file output stream
- Each file your program uses will need a separate file stream object
Streams and Objects
- Streams are objects and thus
cin
andcout
are objects - Objects are special variables that can have a function associated with them
- To call a function of an object, we use the dot operator
- An example of using the dot operator is with
cin
is shown below
cin.fail();
Example of File I/O
- Let us consider an example that reads from a file and writes to a file
- The program reads from a file named
infile.txt
, which contains the following values:10 20 30
- After summing the values, the program writes them to a file named
outfile.txt
- Consider the following code and try to identify:
- What is the name of the input stream?
- Which line opens a file for reading
- What is the name of the output stream?
- Which line opens a file for writing
- Which line reads data from the input stream?
- Which lines write data to the output stream?
Example Program to Read and Write Files
|
//Reads three numbers from the file infile.txt,
//sums the numbers, and writes the sum to the
//file outfile.txt.
#include <fstream> // for file I/O
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
ifstream fin;
fin.open("infile.txt");
if (fin.fail()) {
cout << "Input file opening failed.\n";
exit(-1);
}
ofstream fout;
fout.open("outfile.txt");
if (fout.fail()) {
cout << "Output file opening failed.\n";
exit(-1);
}
int first, second, third;
fin >> first >> second >> third;
fout << "The sum of the first 3\n"
<< "numbers in infile.txt\n"
<< "is " << (first + second + third)
<< endl;
fin.close();
fout.close();
cout << "Processing completed\n";
return 0;
}
|
Closing a Stream
- After finishing reading and writing you should close the file streams
- If you do not close an output stream, you may lose data stored in the output buffer
- In addition, streams consume system resources and you should not keep open any more streams than needed
Procedure For File I/O
- Place the following include directives in your program file:
#include <fstream> // for file I/O #include <iostream> // for cout #include <cstdlib> // for exit() using namespace std;
- Declare names for input and output streams like:
ifstream fin; ofstream fout;
- Connect each stream to a file using
open()
and check for failure:fin.open("infile.txt"); if (fin.fail()) { cout << "Input file failed to open.\n"; exit(-1); } fout.open("outfile.txt"); if (fout.fail()) { cout << "Output file failed to open.\n"; exit(-1); }
- If there is a failure, we need to check that the input file is stored in the same directory that the .cpp file is executing.
- Read or write the data:
- Read from a file with
fin
like usingcin
:fin >> first >> second >> third;
- Write to a file with
fout
like usingcout
:fout << "first = " << first << endl;
- Read from a file with
- Close the streams when finished reading and writing:
fin.close(); fout.close();
More Information
How to Save Your Files Using Eclipse
- If
you are using Eclipse for your assignments in this class, you can
simply save the file in the same project folder as your program (not
under src)
- Right click on the project folder in the project explorer (right side bar)
- Then, go to New->File from the drop down menu that appears
- Name your file using the extension .txt
- Note:
if your project explorer is hidden, go to the following:
Window->Show View->Other...->General->Project Explorer
Activity 20.2: Two Numbers (10 pts)
- In this exercise we write a program that copies two numbers from an input stream to an output stream.
- Copy the following program into a C++ file, save it as
copytwo.cpp
, and then compile and run the starter program to make sure you copied it correctly.#include <iostream> using namespace std; int main() { // Enter your code here return 0; }
- Then, let's create a text file to test our program. Open up a new file in Eclipse by right-clicking the name of the project and selecting New->File.
- Name your file infile.txt.
20
- Stop!! Did you
save the file under the src folder? This is not the correct location.
Drag and drop it into your main project folder.
-
We will read from this file after writing our program.
- Place the following include directives in your source code file:
#include <iostream> // for cout #include <fstream> // for file I/O #include <cstdlib> // for exit() using namespace std;
- Inside
main()
, declare names for the input and output streams:ifstream fin; ofstream fout;
- Add code to connect each stream to a file using
open()
and check for failure:fin.open("infile.txt"); if (fin.fail()) { cout << "Input file failed to open.\n"; exit(-1); } fout.open("outfile.txt"); if (fout.fail()) { cout << "Output file failed to open.\n"; exit(-1); }
- Add statements to read two numbers from the input stream. For example, here is possible code for reading the first number:
int first; fin >> first;
- Add statements to write the two numbers to the output stream. For example, here is possible code for writing the first number:
fout << "first = " << first << endl;
- Close the streams when finished reading and writing:
fin.close(); fout.close();
- Compile and run your modified program to make sure you made the changes correctly.
Notice that you do not see any output on the screen for file reading or writing. The output stream wrote the program output to the output file.
- Save your program source code file to submit to Canvas
Listing of copytwo.cpp
Using Loops to Read Files
Example Program Reading a File Using a Loop
Activity 20.3: Averages (10pts)
#include <iostream> using namespace std; int main() { return 0; }
#include <fstream> #include <cstdlib>
ifstream fin;
fin.open("numbers.txt");
if (fin.fail()) { cout << "Input file failed to open.\n"; exit(-1); }
1. The sum of the numbers 2. How many numbers there are
double sum = 0.0; int count = 0;
double num;
while (fin >> num) { cout << "Processing the number: " << num << endl; sum += num; //adding the number to our running total for the sum count++; //counting how many numbers are in the file }
cout << "The average is: " << sum/count << endl;
ofstream fout;
fout.open("average.txt");
if (fout.fail()) { cout << "Output file failed to open." << endl; exit(-1); }
fout << "The average is: " << sum/count << endl;
fin.close(); fout.close();
10 20 30 40 50
Reading Files using
|
|
#include <fstream> // for file I/O
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
ifstream fin;
fin.open("infile.txt");
if (fin.fail()) {
cout << "Input file failed to open.\n";
exit(-1);
}
string line;
int count = 1;
while(getline(fin, line)) {
cout << "Line " << count << ": "
<< line << endl;
count++;
}
fin.close();
return 0;
} |
Activity 20.4: Sonnet Statistics (10 pts)
- Open up a new C++ file named statistics.cpp and add the starter code below to it:
#include <iostream>
//Add library for file I/O
//Add library for exit()
using namespace std;
int main()
{
int count = 0;
string word, line;
return 0;
}
Now, create a new text file in Eclipse called sonnet.txt and copy and paste the below sonnet into your file:
- We are going to write some code to count the number of words and the number of lines in this file.
- First, declare a new input stream variable named fin.
ifstream fin;
- Next, open up sonnet.txt for reading.
fin.open("sonnet.txt");
- Don't forget to check for failure!
{
cout << "Input file failed to open!" << endl;
exit(-1);
}
- Note that I have provided you with the code above, but you will need to know it from your own memory for the final!
- You can practice by remembering the code for the output stream.
- Beneath your if statement to check for input file failure, create a new output stream variable named fout.
- Then, open up a new text file named statistics.txt for writing.
- Don't forget to check for failure!
- Now, let's write a while loop to count up how many words are in the file.
- Will you need getline(fin, line) or will you need fin >> word?
- Finally, write an fout statement to print the number of words contained in the file:
- Now, close your input file stream.
- Now, we need to count the number of lines in the file.
- For this purpose, we are going to need a new input file stream as we already used the previous one to count the number of words in the file (and we cannot reset the input stream to point to the beginning of the file).
- Add the following code to your program below the statement to close fin:
- Next, we are going to write a while loop to count the number of lines in the file.
- Do we need getline(fin2, line) or fin2 >> line as the test condition of our while loop?
count = 0; //reset count variable to 0
while (?????) {
count++;
}
- Write an fout statement to print out the number of lines in the sonnet.
- Finally, close fin2 and fout and run your program.
- Note that the sonnet has 114 words and 14 lines.
- Did you get the expected result inside of statistics.txt?
- Submit your code to Canvas when you are finished.
}