Follow
Publications: 120 | Followers: 1

Text File I_O - cs.uky.edu

Publish on Category: Birds 0

Text File I/O
Reading Data FromandWriting Data ToText Files
Text File I/O
C++ Provides aFile Streamlibraryto read/write Text Filesusing syntax similar tocin/cout#include <fstream>
Text File I/O
Text files must beOpenedbefore they can beread from or written to,with aFile Namespecified.They should also beClosedafter use.
Text File I/O
#include <fstream>–defines the following:ofstream– data type used to declare aFile Handle(variable) used towriteto a Text File.ifstream– data type used to declare aFile Handle(variable) used toreadfrom aText File.
ofstream
Algorithm:Towritedata to a text file:-declareanofstreamfile handle- (try to)openthe file- if the file opened successfully, use the file handleexactly ascoutis used.-closethe file when done(forgetting this may result in lost data!)
ofstream
#include <fstream>void main() {ofstreamf;f.open(”mydata.txt”);if (!f.fail()) {f<< ”Hello world ” <<endl;f<<setw(10) << 3.14159;f.close();}}
ofstream
ofstreamf;This declaration statement allocates aFile Handlevariable namedfthat can be used to write data to a file.Think of it as a “pipeline to a file”.Currently the “pipeline” is not connected to any file.
ofstream
f.open(”mydata.txt”);This statementtriesto open a file called ”mydata.txt”It may fail or succeed.If it succeeds, it “connects the pipeline” to the file.
ofstream
f.open(”mydata.txt”);If the file does not already exist, it will create a new file.If the file does already exist:IT WILLERASETHE CURRENT CONTENTS OF THE FILE!
ofstream
f.open(”mydata.txt”);Without aPathin the file name, it is assumed the file is in theWorking Directory(Folder).Where is theWorking Directory? It depends, usually:- the same folder as the executable (.exe)- when using the Debugger in MS-VS, in the samefolder as the source (.cpp)
ofstream
f.open(”mydata.txt”);Optionally, the complete path may be included in the file name:f.open(”c:\\datafiles\\joiner\\mydata.txt”);
ofstream
”c:\\datafiles\\joiner\\mydata.txt”Why the double backslashes?!?Remember, for C++ string literals, a backslash is interpreted as “escape character coming up next”, and “\\” is interpreted as a SINGLE backslash.So the above C++ string literal actually means:c:\datafiles\joiner\mydata.txt
ofstream
A string variable or constant may beused for thefile name.stringfn= ”c:\\files\\mydata.txt”;f.open(fn);
ofstream
A string variablecan be used to get the file name from the user:stringfname;cout<< ”Enter the file name: ”;cin>>fname;f.open(fname);But the user should NOT use\\for\(That silly escape character stuff is only for Programmers)
ofstream
ofstreamf(filename);As a “shortcut”, a File Handle may be declaredand opened with one statement:ofstreamf (”mydata.txt”);is the same as:ofstreamf;f.open(”mydata.txt”);
ofstream
f.fail()It is possible that opening the file may fail for some reason (more likely withifstream’s: see below).So the program should check every time.open()is used to ensure the file actually did open.The.fail()function returnstrueorfalse, and so may be used a conditional expression.
ofstream
f.fail()Examplef.open(”mydata.txt”);if (f.fail()) {cout<< ”Failed to open file.\n”;return;// or do whatever the specs say}
ofstream
f <<Once the file is successfully open, use theFile Handle the same ascoutis used.Instead of printing on the screen, the textis written to the file.f << ”Fed Tax: ” <<setw(10)<<fedTax<<endl;
ofstream
f.close();Once all data is written to the file, it should be closed.Failure to do so may mean the last charactersinserted into to the file handle may not actuallybe written to the file (data is lost).
ofstream
#include <fstream>void main() {ofstreamf;f.open(”mydata.txt”);if (!f.fail()) {f<< ”Hello world ” <<endl;f<<setw(10) << 3.14159;f.close();}}
ifstream
Useifstreamas a Data Type to create a File Handle used toreaddata from a text file.Most syntax/issues of usingofstreamsapply to usingifstreams.The main issue withifstreamsis not syntax/semantics, but isAlgorithm Design
ifstream
#include <fstream>void main() {ifstreamf;string name;intage; floatgpa;f.open(”mydata.txt”);if (!f.fail()) {f >> name >> age >>gpa;f.close();}}
ifstream
f.open().open() forifstreamshas the same issues as forofstreams, with one exception:If the filedoes not exist,the .open()fails.
ifstream
f >>Use the extraction operator on the file handle just as is used withcin.Differences withcin:-does NOT suspendthe program to waitfor the user (data is not coming fromthe keyboard!).-no promptsare needed (no human to ask!)
Design of Reading Files
TheAlgorithmfor reading a text fileis dictated by theFormat/Layout of the File.
Design of Reading Files
See morein thein-classexamples

0

Embed

Share

Upload

Make amazing presentation for free
Text File I_O - cs.uky.edu