CS 103 | File I/O | Unit 4e |
Unit 4e – File I/O
Mark Redekopp
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 2
getline() Member Function and Lines of Text
• cin stops reading at whitespace #include <iostream>
using namespace std;
▪ If you want to read a whole line of int main ()
{
text use [Link]() char mytext[80];
cout << "Enter your full name" << endl;
[Link](mytext, 80);
o It will read spaces and tabs but // vs. cin >> mytext;
STOPS at '\n' int last=0;
for(int i=0; i<80; i++){
▪ [Link](char *buffer, if(mytext[i] == ' '){
last = i+1;
int max_chars) break;
}
o Reads max_chars-1 leaving space for }
cout << "Last name starts at index: ";
the null character cout << last << endl;
return 0;
}
Enter your full name
Tommy Trojan
Last name starts at index 6.
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 3
Input Stream Error Checking
#include <iostream>
• We can check errors when cin receives using namespace std;
unexpected data that can’t be converted int main ()
to the given type {
int x, y;
• Use the function fail() member function cout << "Enter an int: " << endl;
(i.e. [Link]()) which returns true if cin >> x; // What if the user enters:
// "abc"
anything went wrong opening or reading
data in from the file (will continue to // Check if we successfully read an int
if( [Link]() ) {
return true from then on until you cout << "Error: I said enter an int!";
cout << " Now I must exit!" << endl;
perform [Link]()) return 1;
• For now (in CS103), print an error and } else {
cout << "You did it! You entered an int";
exit. }
cout << " with value: " << x << endl;
cin >> y; // Will fail regardless
if( [Link]() ) { ... } // always true
return 0;
}
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e |
Getting data into and out of files stored on disk using ifstream and ofstream objects
SIMPLE FILE I/O USING FILESTREAM
OBJECTS
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 5
File I/O Intro
• What methods does a user have to provide a program input:
▪ cin
▪ Command line (argc, argv)
• Now a third method: File I/O (accessing data in files)
• Primary method for a program to read/write files:
▪ File streams [Main subject of our lecture]
▪ I/O Redirection [Subject of a later lecture] which uses the OS to "redirect"
input and output from cin and cout to files instead of the keyboard and
monitor.
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 6
Important Fact
• For your program to operate on DISK
[Link]
data in a file… 15 21
hello
• …you must read it into a variable
• Everything we will see ./app1
subsequently is simply how to ifstream
▪ Get data from a file into a variable, or
▪ Take data from a variable and save it
to a file
Your program variables:
x 15 y 21
./app1
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 7
Overview
• Two methods for file I/O DISK
▪ File streams (ifstream and [Link]
15 21
ofstream) are part of the C++ hello
library and perform file I/O
directly through a cin- and cout- ./app1
$ ./app1 < [Link]
like interface I/O redirection via the OS
ifstream
▪ I/O redirection: [More on this 1 5 2 1 \n
later in the semester] input
o The OS reads or writes data ifstream ifile;
ifile >> x >> y
stream:
cin
to/from a file by controlling cin & cin >> x >> y
cout
o The program just performs Your program variables:
normal cin and cout commands x y 21
\n
15
input
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
./app1 stream:
CS 103 | File I/O | Unit 4e | 8
Disk Access
• All code and data (variables) resides in RAM
• Processor can ONLY talk directly to RAM (memory)
▪
0
Cannot access files on disk directly Code
• Files on your disk require special OS routines to …
Globals
204
access their data … 204
▪ The OS provides routines to perform the translation Heap
• C++ provide file streams to abstract those OS
routines and help to …
▪ Take data from a file and input it to your variables or … Stack
(area for MHV2200BT
▪
data local to
Take your variables and writes their values to a file fffffffc a function)
Memory
110010101001…
Data files:
.mpg
.txt
.docx
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 9
Recall: I/O Streams
• C++ and the OS use the notion of streams to temporarily store (aka buffer) data to be input or
output and then uses the cin and cout objects (from the <iostream> library) to access those
streams. (These objects have internal data members and member functions).
• While cin has a stream that receives input from the keyboard and cout has a stream that
outputs to the terminal, the same stream abstraction could be applied to files!
#include<iostream>
int main()
{
std::cout << "It was the" << std::endl;
std::cout << "best of times.";
OS return 0;
}
cout
input stream output stream
memory (aka stdin): 7 5 y ... #include<iostream> memory (aka stdout):
int main()
{ I t w a s t h e \n b e
cin int x; It was
std::cin >> x; the
return 0; OS
}
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
This Photo by Unknown Author is licensed under CC BY-NC
CS 103 | File I/O | Unit 4e | 10
File Streams
• C++ leverages the SAME interface that cin and cout provide to:
▪ Read data IN from a file (like cin, but data comes from a file not the keyboard) and
▪ Write data OUT to a file (like cout, but data goes to a file not the terminal).
• The counterpart to cin is an ifstream object
• The counterpart to cout is an ofstream object
#include <iostream>
#include <fstream>
75 yes
using namespace std;
23 no
int main() {
ofstream ofile("[Link]")
[Link] ofile << "Hi there" << std::endl;
[Link]();
OS return 0;
}
#include <iostream>
#include <fstream> ofstream Hi there
input stream Using namespace std; output stream
memory: 7 5 y ... int main() { memory:
int x; [Link]
ifstream ifile("[Link]"); H i t h e r e \n EOF
ifstream ifile >> x;
// use x
[Link](); OS
return 0;
} or distributed.
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, This Photo by Unknown Author is licensed under CC BY
CS 103 | File I/O | Unit 4e | 11
Input & Output Streams
• To summarize, there are other types of input and output streams
other than cin and cout
• File streams gives the same capabilities as cin and cout, except
data is read/written from/to a file on the hard drive
▪ Everything you do with cin using the '>>' operator you can now use with an
ifstream to access data from a file
▪ Everything you do with cout using the '<<' operator you can now use with
an ofstream to output data to a file
• Let's learn more about streams '>>'…we'll see it in the context of
cin and cout but realize it will apply to other streams we'll learn
about next
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 12
Starting File I/O
• Just like document or image editor allows two
operations on files:
▪ Read info from the file (like 'Open' command)
o Use an 'ifstream' object to open the file
o Read data from the file
o Close it when you're done
▪ Write info to the file (like 'Save As' command)
o Use an 'ofstream' object
o Write the data to a file
o Close it when you're done
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 13
Two Kinds of Files: Binary and Text
• We conceive of files as "streams" (1D arrays) of data
• Files are broken into two types based on how they represent the given
information:
▪ Text files: File is just a large sequence of ASCII characters (every piece of data is just a byte)
▪ Binary files: Data in the file is just bits that can be retrieved in different size chunks (4-byte
int, 8-byte double, etc.)
• Example: Store the number 172 in a file:
▪ Text: Would store 3 ASCII chars '1','7','2' (ASCII 49, 55, 50) requiring 3 bytes (but the key is
each digit or character is stored separately in ASCII)
▪ Binary: If 172 was in an 'int' variable we could store it as 4-bytes in binary rather than
separate ASCII characters.
In this unit, we will only focus on text file I/O
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e |
TEXT FILE I/O
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 15
Text File I/O - ifstream
#include <iostream>
• Must include <fstream> #include <fstream>
using namespace std;
• Use ifstream object/variable for int main ()
reading a file {
int x; double y;
▪ Can do anything 'cin' can do
ifstream ifile ("[Link]");
▪ Must "open" the file (usually by if( [Link]() ){ // able to open file?
specifying the filename when you cout << "Couldn't open file" << endl;
return 1;
create the ifstream }
• Use '>>' operator, .fail(), .getline() ifile >> x >> y;
if ( [Link]() ){
with the ifstream object just as you cout << "Unable to read int & double." << endl;
would on cin but realize operations }
return 1;
are happening on data from the file //...
5 -3.5 return 0;
}
[Link]
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 16
Text File I/O - ofstream
#include <iostream>
• Must include <fstream> #include <fstream>
using namespace std;
• Use ofstream object/variable for int main ()
{
writing to a file int x; double y;
▪ Can do anything 'cout' can do ifstream ifile ("[Link]");
• Use '>>' operator, I/O manipulators, if( [Link]() ){ // able to open file?
cout << "Couldn't open file" << endl;
return 1;
etc. on the stream but realize }
operations are happening on data ifile >> x >> y;
if ( [Link]() ){
form the file cout << "Unable to read int & double." << endl;
return 1;
• Close all filestreams using the .close() }
ofstream ofile("[Link]");
member function ofile << "Int from file is " << x << endl;
ofile << "Double from file is " << y << endl;
5 -3.5 Int from file is 5 [Link]();
Double from file is -3.5 [Link]();
return 0;
[Link] [Link] }
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 17
Getting Lines of Text
• Recall, using the >> operator to get an input string of text
#include <iostream>
#include <fstream>
using namespace std;
(char * or char [] variable passed to cin) implicitly stops at
int main ()
the first whitespace
{
• To get a whole line of text (including spaces) char myline[100]; int i = 1;
▪ [Link](char *buf, int bufsize); ifstream ifile("[Link]");
▪ [Link](char *buf, int bufsize); if( [Link]() ){ // can't open?
return 1;
▪ Reads max of bufsize-1 characters (including newline) }
o Reads and discards the newline and places NULL char at the end of the [Link](myline, 100);
string. while ( ! [Link]()) {
• This program reads all the lines of text from a file and adds
}
cout << i++ << ": " << myline << endl;
[Link](myline, 100);
"line numbers".
[Link]();
return 0;
}
The fox jumped over the log.\n 1: The fox jumped over the log.
The bear ate some honey.\n 2: The bear ate some honey.
The CS student solved a hard problem.\n 3: The CS student solved a hard problem.
[Link]
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.
CS 103 | File I/O | Unit 4e | 18
Activity
• File I/O Exercises
© 2024 by Mark Redekopp. This content is protected and may not be shared, uploaded, or distributed.