SlideShare ist ein Scribd-Unternehmen logo
1 von 106
Chapter 12 – File Operations

1

Starting Out with C++, 3rd Edition
12.1 What is a File?
• A file is a collection on information, usually
stored on a computer’s disk. Information
can be saved to files and then later reused.

2

Starting Out with C++, 3rd Edition
12.2 File Names
• All files are assigned a name that is used for
identification purposes by the operating
system and the user.

3

Starting Out with C++, 3rd Edition
Table 12-1
File Name and Extension

File Contents

M Y P R O G .B A S

BASIC program

M E N U .B A T

DOS Batch File

I N S T A L L .D O C

Documentation File

C R U N C H .E X E

Executable File

B O B .H T M L

HTML (Hypertext Markup Language) File

3 D M O D E L .J A V A

Java program or applet

I N V E N T .O B J

Object File

P R O G 1 .P R J

Borland C++ Project File

A N S I .S Y S

System Device Driver

R E A D M E .T X T

Text File

4

Starting Out with C++, 3rd Edition
12.3 Focus on Software Engineering:
The Process of Using a File
• Using a file in a program is a simple threestep process
– The file must be opened. If the file does not yet
exits, opening it means creating it.
– Information is then saved to the file, read from
the file, or both.
– When the program is finished using the file, the
file must be closed.
5

Starting Out with C++, 3rd Edition
Figure 12-1

6

Starting Out with C++, 3rd Edition
Figure 12-2

7

Starting Out with C++, 3rd Edition
12.4 Setting Up a Program for File
Input/Output
• Before file I/O can be performed, a C++
program must be set up properly.
• File access requires the inclusion of
fstream.h

8

Starting Out with C++, 3rd Edition
12.5 Opening a File
• Before data can be written to or read from a
file, the file must be opened.
ifstream inputFile;
inputFile.open(“customer.dat”);

9

Starting Out with C++, 3rd Edition
Program 12-1
// This program demonstrates the declaration of an fstream
// object and the opening of a file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile; // Declare file stream object
char fileName[81];
cout << "Enter the name of a file you wish to openn";
cout << "or create: ";
cin.getline(fileName, 81);
dataFile.open(fileName, ios::out);
cout << "The file " << fileName << " was opened.n";
}

10

Starting Out with C++, 3rd Edition
Program Output with Example Input
Enter the name of a file you wish to open
or create: mystuff.dat [Enter]
The file mystuff.dat was opened.

11

Starting Out with C++, 3rd Edition
Table 12-3
File Type

Default Open Mode

o fs tre a m

The file is opened for output only. (Information may be
written to the file, but not read from the file.) If the file
does not exist, it is created. If the file already exists, its
contents are deleted (the file is truncated).

ifs tre a m

The file is opened for input only. (Information may be
read from the file, but not written to it.) The file’s
contents will be read from its beginning. If the file does
not exist, the open function fails.

12

Starting Out with C++, 3rd Edition
Table 12-4
File Mode Flag

Meaning

io s ::a p p

Append mode. If the file already exists, its
contents are preserved and all output is
written to the end of the file. By default, this
flag causes the file to be created if it does
not exist.

io s ::a te

If the file already exists, the program goes
directly to the end of it. Output may be
written anywhere in the file.

io s ::b in a ry

Binary mode. When a file is opened in
binary mode, information is written to or
read from it in pure binary format. (The
default mode is text.)

io s ::in

Input mode. Information will be read from
the file. If the file does not exist, it will not
be created and the open function will fail.
13

Starting Out with C++, 3rd Edition
Table 12-4 continued
File Mode
Flag

Meaning

io s ::n o c re a te

If the file does not already exist, this flag
will cause the open function to fail. (The file
will not be created.)

io s ::n o re p la c e

If the file already exists, this flag will cause
the open function to fail. (The existing file
will not be opened.)

io s ::o u t

Output mode. Information will be written to
the file. By default, the file’s contents will
be deleted if it already exists.

io s ::tru n c

If the file already exists, its contents will be
deleted (truncated). This is the default
mode used by io s ::o u t.

14

Starting Out with C++, 3rd Edition
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in |
ios::out);

15

Starting Out with C++, 3rd Edition
Program 12-2
// This program demonstrates the opening of a file at the
// time the file stream object is declared.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile("names.dat", ios::in | ios::out);
cout << "The file names.dat was opened.n";
}

16

Starting Out with C++, 3rd Edition
Program Output with Example Input
The file names.dat was opened.

17

Starting Out with C++, 3rd Edition
Testing for Open Errors
dataFile.open(“cust.dat”, ios::in);
if (!dataFile)
{
cout << “Error opening file.n”;
}

18

Starting Out with C++, 3rd Edition
Another way to Test for Open Errors
dataFile.open(“cust.dat”, ios::in);
if (dataFile.fail())
{
cout << “Error opening file.n”;
}

19

Starting Out with C++, 3rd Edition
12.6 Closing a File
• A file should be closed when a program is
finished using it.

20

Starting Out with C++, 3rd Edition
Program 12-3
// This program demonstrates the close function.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
dataFile.open("testfile.txt", ios::out);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
cout << "File was created successfully.n";
cout << "Now closing the file.n";
dataFile.close();
}

21

Starting Out with C++, 3rd Edition
Program Output
File was created successfully.
Now closing the file.

22

Starting Out with C++, 3rd Edition
12.7 Using << to Write Information to a
File
• The stream insertion operator (<<) may be
used to write information to a file.
outputFile << “I love C++ programming !”

23

Starting Out with C++, 3rd Edition
Program 12-4
// This program uses the << operator to write information to a file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
char line[81];
dataFile.open("demofile.txt", ios::out);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
24

Starting Out with C++, 3rd Edition
Program continues
cout << "File opened successfully.n";
cout << "Now writing information to the file.n";
dataFile << "Jonesn";
dataFile << "Smithn";
dataFile << "Willisn";
dataFile << "Davisn";
dataFile.close();
cout << "Done.n";
}

25

Starting Out with C++, 3rd Edition
Program Screen Output
File opened successfully.
Now writing information to the file.
Done.

Output to File demofile.txt
Jones
Smith
Willis
Davis

26

Starting Out with C++, 3rd Edition
Figure 12-3

27

Starting Out with C++, 3rd Edition
Program 12-5
// This program writes information to a file, closes the file,
// then reopens it and appends more information.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;

}

dataFile.open("demofile.txt", ios::out);
dataFile << "Jonesn";
dataFile << "Smithn";
dataFile.close();
dataFile.open("demofile.txt", ios::app);
dataFile << "Willisn";
dataFile << "Davisn";
dataFile.close();
28

Starting Out with C++, 3rd Edition
Output to File demofile.txt
Jones
Smith
Willis
Davis

29

Starting Out with C++, 3rd Edition
12.8 File Output Formatting
• File output may be formatted the same way
as screen output.

30

Starting Out with C++, 3rd Edition
Program 12-6
// This program uses the precision member function of a
// file stream object to format file output.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
float num = 123.456;
dataFile.open("numfile.txt", ios::out);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
31

Starting Out with C++, 3rd Edition
Program continues
dataFile << num << endl;
dataFile.precision(5);
dataFile << num << endl;
dataFile.precision(4);
dataFile << num << endl;
dataFile.precision(3);
dataFile << num << endl;
}

32

Starting Out with C++, 3rd Edition
Contents of File numfile.txt
123.456
123.46
123.5
124

33

Starting Out with C++, 3rd Edition
Program 12-7
#include <iostream.h>

#include <fstream.h>
#include <iomanip.h>
void main(void)
{ fstream outFile("table.txt", ios::out);
int nums[3][3] = { 2897, 5, 837,
34, 7, 1623,
390, 3456, 12 };
// Write the three rows of numbers
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
outFile << setw(4) << nums[row][col] << " ";
}
outFile << endl;
}
outFile.close();
}

34

Starting Out with C++, 3rd Edition
Contents of File TABLE.TXT
2897
5 837
34
7 1623
390 3456
12

35

Starting Out with C++, 3rd Edition
Figure 12-6

36

Starting Out with C++, 3rd Edition
12.9 Using >> to Read Information from
a File
• The stream extraction operator (>>) may be
used to read information from a file.

37

Starting Out with C++, 3rd Edition
Program 12-8
// This program uses the >> operator to read information from a file.

#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile;
char name[81];
dataFile.open("demofile.txt", ios::in);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
cout << "File opened successfully.n";
cout << "Now reading information from the file.nn";
38

Starting Out with C++, 3rd Edition
Program continues
for (int count = 0; count < 4; count++)
{
dataFile >> name;
cout << name << endl;
}
dataFile.close();
cout << "nDone.n";
}

39

Starting Out with C++, 3rd Edition
Program Screen Output
File opened successfully.
Now reading information from the file.
Jones
Smith
Willis
Davis
Done.

40

Starting Out with C++, 3rd Edition
12.10 Detecting the End of a File
• The eof() member function reports when
the end of a file has been encountered.
if (inFile.eof())
inFile.close();

41

Starting Out with C++, 3rd Edition
Program 12-9
// This program uses the file stream object's eof() member
// function to detect the end of the file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile;
char name[81];
dataFile.open("demofile.txt", ios::in);
if (!dataFile)
{
cout << "File open error!" << endl;
return;
}
cout << "File opened successfully.n";
cout << "Now reading information from the file.nn";
42

Starting Out with C++, 3rd Edition
Program continues
dataFile >> name; // Read first name from the file
while (!dataFile.eof())
{
cout << name << endl;
dataFile >> name;
}
dataFile.close();
cout << "nDone.n";
}

43

Starting Out with C++, 3rd Edition
Program Screen Output
File opened successfully.
Now reading information from the file.
Jones
Smith
Willis
Davis
Done.

44

Starting Out with C++, 3rd Edition
Note on eof()
• In C++, “end of file” doesn’t mean the
program is at the last piece of information
in the file, but beyond it. The eof()
function returns true when there is no more
information to be read.

45

Starting Out with C++, 3rd Edition
12.11 Passing File Stream Objects to
Functions
• File stream objects may be passed by reference to
functions.
bool openFileIn(fstream &file, char name[51])
{
bool status;
file.open(name, ios::in);
if (file.fail())
status = false;
else
status = true;
return status;
}

46

Starting Out with C++, 3rd Edition
12.12 More Detailed Error Testing
• All stream objects have error state bits that
indicate the condition of the stream.

47

Starting Out with C++, 3rd Edition
Table 12-5
Bit

Description

io s ::e o fb it

Set when the end of an input stream is
encountered.
Set when an attempted operation has failed.
Set when an unrecoverable error has occurred.
Set when an invalid operation has been
attempted.
Set when all the flags above are not set.
Indicates the stream is in good condition.

io s ::fa ilb it
io s ::h a rd fa il
io s ::b a d b it
io s ::g o o d b it

48

Starting Out with C++, 3rd Edition
Table 12-6
Function

Description

e o f()

Returns true (non-zero) if the eofbit flag is set,
otherwise returns false.
Returns true (non-zero) if the failbit or hardfail
flags are set, otherwise returns false.
Returns true (non-zero) if the badbit flag is set,
otherwise returns false.
Returns true (non-zero) if the goodbit flag is
set, otherwise returns false.
When called with no arguments, clears all the
flags listed above. Can also be called with a
specific flag as an argument.

fa il()
b a d ()
g o o d ()
c le a r()

49

Starting Out with C++, 3rd Edition
Program 12-11
// This program demonstrates the return value of the stream
// object error testing member functions.
#include <iostream.h>
#include <fstream.h>
// Function prototype
void showState(fstream &);
void main(void)
{
fstream testFile("stuff.dat", ios::out);
if (testFile.fail())
{
cout << "cannot open the file.n";
return;
}
50

Starting Out with C++, 3rd Edition
Program continues

int num = 10;
cout << "Writing to the file.n";
testFile << num;
// Write the integer to
testFile
showState(testFile);
testFile.close();
// Close the file
testFile.open("stuff.dat", ios::in);
// Open for input
if (testFile.fail())
{
cout << "cannot open the file.n";
return;
}

51

Starting Out with C++, 3rd Edition
Program continues

}

cout << "Reading from the file.n";
testFile >> num;
// Read the only number in the file
showState(testFile);
cout << "Forcing a bad read operation.n";
testFile >> num;
// Force an invalid read operation
showState(testFile);
testFile.close();
// Close the file

// Definition of function ShowState. This function uses
// an fstream reference as its parameter. The return values of
// the eof(), fail(), bad(), and good() member functions are
// displayed. The clear() function is called before the function
// returns.

52

Starting Out with C++, 3rd Edition
Program continues
void showState(fstream &file)
{
cout << "File Status:n";
cout << " eof bit: " << file.eof() << endl;
cout << " fail bit: " << file.fail() << endl;
cout << " bad bit: " << file.bad() << endl;
cout << " good bit: " << file.good() << endl;
file.clear(); // Clear any bad bits
}

53

Starting Out with C++, 3rd Edition
Program Output
Writing to the file.
File Status:
eof bit: 0
fail bit: 0
bad bit: 0
good bit: 1
Reading from the file.
File Status:
eof bit: 0
fail bit: 0
bad bit: 0
good bit: 1
Forcing a bad read operation.
File Status:
eof bit: 1
fail bit: 2
bad bit: 0
good bit: 0
54

Starting Out with C++, 3rd Edition
12.13 Member Functions for Reading
and Writing Files
• File stream objects have member functions
for more specialized file reading and
writing.

55

Starting Out with C++, 3rd Edition
Figure 12-8

56

Starting Out with C++, 3rd Edition
Program 12-12
// This program uses the file stream object's eof() member
// function to detect the end of the file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream nameFile;
char input[81];
nameFile.open("murphy.txt", ios::in);
if (!nameFile)
{
cout << "File open error!" << endl;
return;
}

57

Starting Out with C++, 3rd Edition
Program 12-12 (continued)
nameFile >> input;
while (!nameFile.eof())
{
cout << input;
nameFile >> input;
}
nameFile.close();
}

58

Starting Out with C++, 3rd Edition
Program Screen Output
JayneMurphy47JonesCircleAlmond,NC28702

59

Starting Out with C++, 3rd Edition
The getline Member Function
• dataFile.getline(str, 81, ‘n’);
str – This is the name of a character array, or a pointer to a
section of memory. The information read from the file will be
stored here.
81 – This number is one greater than the maximum number of
characters to be read. In this example, a maximum of 80
characters will be read.
‘n’ – This is a delimiter character of your choice. If this
delimiter is encountered, it will cause the function to stop
reading before it has read the maximum number of characters.
(This argument is optional. If it’s left our, ‘n’ is the default.)
60

Starting Out with C++, 3rd Edition
Program 12-13
// This program uses the file stream object's getline member
// function to read a line of information from the file.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream nameFile;
char input[81];
nameFile.open("murphy.txt", ios::in);
if (!nameFile)
{
cout << "File open error!" << endl;
return;
}

61

Starting Out with C++, 3rd Edition
Program continues
nameFile.getline(input, 81); // use n as a delimiter
while (!nameFile.eof())
{
cout << input << endl;
nameFile.getline(input, 81); // use n as a delimiter
}
nameFile.close();
}

62

Starting Out with C++, 3rd Edition
Program Screen Output
Jayne Murphy
47 Jones Circle
Almond, NC 28702

63

Starting Out with C++, 3rd Edition
Program 12-14
// This file shows the getline function with a user// specified delimiter.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream dataFile("names2.txt", ios::in);
char input[81];
dataFile.getline(input, 81, '$');
while (!dataFile.eof())
{
cout << input << endl;
dataFile.getline(input, 81, '$');
}
dataFile.close();
}

64

Starting Out with C++, 3rd Edition
Program Output
Jayne Murphy
47 Jones Circle
Almond, NC 28702
Bobbie Smith
217 Halifax Drive
Canton, NC 28716
Bill Hammet
PO Box 121
Springfield, NC 28357

65

Starting Out with C++, 3rd Edition
The get Member Function
inFile.get(ch);

66

Starting Out with C++, 3rd Edition
Program 12-15
// This program asks the user for a file name. The file is
// opened and its contents are displayed on the screen.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream file;
char ch, fileName[51];
cout << "Enter a file name: ";
cin >> fileName;
file.open(fileName, ios::in);
if (!file)
{
cout << fileName << “ could not be opened.n";
return;
}

67

Starting Out with C++, 3rd Edition
Program continues

file.get(ch);
// Get a character
while (!file.eof())
{
cout << ch;
file.get(ch);
// Get another character
}
file.close();
}

68

Starting Out with C++, 3rd Edition
The put Member Function
• outFile.put(ch);

69

Starting Out with C++, 3rd Edition
Program 12-16
// This program demonstrates the put member function.
#include <iostream.h>
#include <fstream.h>
void main(void)
{ fstream dataFile("sentence.txt", ios::out);
char ch;
cout << "Type a sentence and be sure to end it with a ";
cout << "period.n";
while (1)
{
cin.get(ch);
dataFile.put(ch);
if (ch == '.')
break;
}
dataFile.close();
}
70

Starting Out with C++, 3rd Edition
Program Screen Output with Example Input
Type a sentence and be sure to end it with a
period.
I am on my way to becoming a great programmer. [Enter]

Resulting Contents of the File SENTENCE.TXT:
I am on my way to becoming a great programmer.

71

Starting Out with C++, 3rd Edition
12.14 Focus on Software Engineering:
Working with Multiple Files
• It’s possible to have more than one file open
at once in a program.

72

Starting Out with C++, 3rd Edition
Program 12-17
// This program demonstrates reading from one file and writing
// to a second file.
#include <iostream.h>
#include <fstream.h>
#include <ctype.h> // Needed for the toupper function
void main(void)
{
ifstream inFile;
ofstream outFile("out.txt");
char fileName[81], ch, ch2;
cout << "Enter a file name: ";
cin >> fileName;
inFile.open(fileName);
if (!inFile)
{
cout << "Cannot open " << fileName << endl;
return;
}
73

Starting Out with C++, 3rd Edition
Program continues
inFile.get(ch);
// Get a characer from file 1
while (!inFile.eof()) // Test for end of file
{
ch2 = toupper(ch); // Convert to uppercase
outFile.put(ch2); // Write to file2
inFile.get(ch);
// Get another character from file 1
}
inFile.close();
outFile.close();
cout << "File conversion done.n";
}

74

Starting Out with C++, 3rd Edition
Program Screen Output with Example Input
Enter a file name: hownow.txt [Enter]
File conversion done.
Contents of hownow.txt:
how now brown cow.
How Now?
Resulting Contents of out.txt:
HOW NOW BROWN COW.
HOW NOW?

75

Starting Out with C++, 3rd Edition
12.15 Binary Files
• Binary files contain data that is
unformatted, and not necessarily stored as
ASCII text.
file.open(“stuff.dat”, ios::out | ios::binary);

76

Starting Out with C++, 3rd Edition
Figure 12-9

77

Starting Out with C++, 3rd Edition
Figure 12-10

78

Starting Out with C++, 3rd Edition
Program 12-18
// This program uses the write and read functions.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream file(“NUMS.DAT", ios::out | ios::binary);
int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,

10};

cout << "Now writing the data to the file.n";
file.write((char*)buffer, sizeof(buffer));
file.close();
file.open("NUMS.DAT", ios::in); // Reopen the file.
cout << "Now reading the data back into memory.n";
file.read((char*)buffer, sizeof(buffer));
for (int count = 0; count < 10; count++)
cout << buffer[count] << " ";
file.close();
}

79

Starting Out with C++, 3rd Edition
Program Screen Output
Now writing the data to the file.
Now reading the data back into memory.
1 2 3 4 5 6 7 8 9 10

80

Starting Out with C++, 3rd Edition
12.16 Creating Records with Structures
• Structures may be used to store fixed-length
records to a file.
struct Info
{
char name[51];
int age;
char address1[51];
char address2[51];
char phone[14];
};

• Since structures can contain a mixture of data
types, you should always use the ios::binary mode
when opening a file to store them.
81

Starting Out with C++, 3rd Edition
Program 12-19
// This program demonstrates the use of a structure variable to
// store a record of information to a file.
#include <iostream.h>
#include <fstream.h>
#include <ctype.h> // for toupper
// Declare a structure for the record.
struct Info
{
char name[51];
int age;
char address1[51];
char address2[51];
char phone[14];
};

82

Starting Out with C++, 3rd Edition
Program continues
void main(void)
{
fstream people("people.dat", ios::out | ios::binary);
Info person;
char again;
if (!people)
{
cout << "Error opening file. Program aborting.n";
return;
}
do
{
cout << "Enter the following information about a ”
<< "person:n";
cout << "Name: ";

83

Starting Out with C++, 3rd Edition
Program continues
cin.getline(person.name, 51);
cout << "Age: ";
cin >> person.age;
cin.ignore(); // skip over remaining newline.
cout << "Address line 1: ";
cin.getline(person.address1, 51);
cout << "Address line 2: ";
cin.getline(person.address2, 51);
cout << "Phone: ";
cin.getline(person.phone, 14);
people.write((char *)&person, sizeof(person));
cout << "Do you want to enter another record? ";
cin >> again;
cin.ignore();
} while (toupper(again) == 'Y');
people.close();
}
84

Starting Out with C++, 3rd Edition
Program Screen Output with Example Input
Enter the following information about a person:
Name: Charlie Baxter [Enter]
Age: 42 [Enter]
Address line 1: 67 Kennedy Bvd. [Enter]
Address line 2: Perth, SC 38754 [Enter]
Phone: (803)555-1234 [Enter]
Do you want to enter another record? Y [Enter]
Enter the following information about a person:
Name: Merideth Murney [Enter]
Age: 22 [Enter]
Address line 1: 487 Lindsay Lane [Enter]
Address line 2: Hazelwood, NC 28737 [Enter]
Phone: (704)453-9999 [Enter]
Do you want to enter another record? N [Enter]

85

Starting Out with C++, 3rd Edition
12.17 Random Access Files
• Random Access means non-sequentially
accessing informaiton in a file.
Figure 12-11

86

Starting Out with C++, 3rd Edition
Table 12-7
Mode Flag

Description

io s ::b e g

The offset is calculated from
the beginning of the file.

io s ::e n d

The offset is calculated from
the end of the file.

io s ::c u r

The offset is calculated from
the current position.

87

Starting Out with C++, 3rd Edition
Table 12-8
Statement

How it Affects the Read/Write Position

F ile .s e e k p ( 3 2 L , io s ::b e g ) ;

Sets the write position to the 33rd byte
(byte 32) from the beginning of the file.

file .s e e k p ( - 1 0 L , io s ::e n d ) ;

Sets the write position to the 11th byte
(byte 10) from the end of the file.

file .s e e k p ( 1 2 0 L , io s ::c u r ) ;

Sets the write position to the 121st byte
(byte 120) from the current position.

file .s e e k g ( 2 L , io s ::b e g ) ;

Sets the read position to the 3rd byte
(byte 2) from the beginning of the file.

file .s e e k g ( - 1 0 0 L , io s ::e n d ) ;

Sets the read position to the 101st byte
(byte 100) from the end of the file.

file .s e e k g ( 4 0 L , io s ::c u r ) ;

Sets the read position to the 41st byte
(byte 40) from the current position.

file .s e e k g ( 0 L , io s ::e n d ) ;

Sets the read position to the end of the
file.

88

Starting Out with C++, 3rd Edition
Program 12-21
// This program demonstrates the seekg function.
#include <iostream.h>
#include <fstream.h>
void main(void)
{
fstream file("letters.txt", ios::in);
char ch;
file.seekg(5L, ios::beg);
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;

89

Starting Out with C++, 3rd Edition
Program continues
file.seekg(3L, ios::cur);
file.get(ch);
cout << "Byte 3 from current: " << ch << endl;
file.close();
}

90

Starting Out with C++, 3rd Edition
Program Screen Output
Byte 5 from beginning: f
Byte 10 from end: q
Byte 3 from current: u

91

Starting Out with C++, 3rd Edition
The tellp and tellg Member
Functions
• tellp returns a long integer that is the
current byte number of the file’s write
position.
• tellg returns a long integer that is the
current byte number of the file’s read
position.

92

Starting Out with C++, 3rd Edition
Program 12-23
// This program demonstrates the tellg function.
#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
// For toupper
void main(void)
{
fstream file("letters.txt", ios::in);
long offset;
char ch, again;
do
{
cout << "Currently at position " << file.tellg() << endl;
cout << "Enter an offset from the beginning of the file: ";
cin >> offset;

93

Starting Out with C++, 3rd Edition
Program continues
file.seekg(offset, ios::beg);
file.get(ch);
cout << "Character read: " << ch << endl;
cout << "Do it again? ";
cin >> again;
} while (toupper(again) == 'Y');
file.close();
}

94

Starting Out with C++, 3rd Edition
Program Output with Example Input
Currently at position 0
Enter an offset from the beginning of the file: 5
[Enter]
Character read: f
Do it again? y [Enter]
Currently at position 6
Enter an offset from the beginning of the file: 0
[Enter]
Character read: a
Do it again? y [Enter]
Currently at position 1
Enter an offset from the beginning of the file: 20
[Enter]
Character read: u
Do it again? n [Enter]
95

Starting Out with C++, 3rd Edition
12.18 Opening a File for Both Input and
Output
• You may perform input and output on an fstream
file without closing it and reopening it.
fstream file(“data.dat”, ios::in | ios::out);

96

Starting Out with C++, 3rd Edition
Program 12-24
// This program sets up a file of blank inventory records.
#include <iostream.h>
#include <fstream.h>
// Declaration of Invtry structure
struct Invtry
{
char desc[31];
int qty;
float price;
};
void main(void)
{
fstream inventory("invtry.dat", ios::out | ios::binary);
Invtry record = { "", 0, 0.0 };

97

Starting Out with C++, 3rd Edition
Program continues
// Now write the blank records
for (int count = 0; count < 5; count++)
{
cout << "Now writing record " << count << endl;
inventory.write((char *)&record, sizeof(record));
}
inventory.close();
}

98

Starting Out with C++, 3rd Edition
Program Screen Output
Now
Now
Now
Now
Now

writing
writing
writing
writing
writing

record
record
record
record
record

0
1
2
3
4

99

Starting Out with C++, 3rd Edition
Program 12-25
// This program displays the contents of the inventory file.
#include <iostream.h>
#include <fstream.h>
// Declaration of Invtry structure
struct Invtry
{
char desc[31];
int qty;
float price;
};
void main(void)
{
fstream inventory("invtry.dat", ios::in | ios::binary);
Invtry record = { "", 0, 0.0 };

100

Starting Out with C++, 3rd Edition
Program continues
// Now read and display the records
inventory.read((char *)&record, sizeof(record));
while (!inventory.eof())
{
cout << "Description: ";
cout << record.desc << endl;
cout << "Quantity: ";
cout << record.qty << endl;
cout << "Price: ";
cout << record.price << endl << endl;
inventory.read((char *)&record, sizeof(record));
}
inventory.close();
}

101

Starting Out with C++, 3rd Edition
Here is the screen output of Program 12-25 if it is run
immediately after Program 12-24 sets up the file of blank
records.
Program Screen Output
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
Description:
Quantity: 0
Price: 0.0
102

Starting Out with C++, 3rd Edition
Program 12-26
// This program allows the user to edit a specific record in
// the inventory file.
#include <iostream.h>
#include <fstream.h>
// Declaration of Invtry structure
struct Invtry
{
char desc[31];
int qty;
float price;
};
void main(void)
{

103

Starting Out with C++, 3rd Edition
Program continues
fstream inventory("invtry.dat", ios::in | ios::out |
Invtry record;
long recNum;
cout << "Which record do you want to edit?";
cin >> recNum;
inventory.seekg(recNum * sizeof(record), ios::beg);
inventory.read((char *)&record, sizeof(record));
cout << "Description: ";
cout << record.desc << endl;
cout << "Quantity: ";
cout << record.qty << endl;
cout << "Price: ";
cout << record.price << endl;
cout << "Enter the new data:n";
cout << "Description: ";

ios::binary);

104

Starting Out with C++, 3rd Edition
Program continues
cin.ignore();
cin.getline(record.desc, 31);
cout << "Quantity: ";
cin >> record.qty;
cout << "Price: ";
cin >> record.price;
inventory.seekp(recNum * sizeof(record), ios::beg);
inventory.write((char *)&record, sizeof(record));
inventory.close();
}

105

Starting Out with C++, 3rd Edition
Program Screen Output with Example Input
Which record do you ant to edit? 2 [Enter]
Description:
Quantity: 0
Price: 0.0
Enter the new data:
Description: Wrench [Enter]
Quantity: 10 [Enter]
Price: 4.67 [Enter]

106

Starting Out with C++, 3rd Edition

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Call by value
Call by valueCall by value
Call by value
 
Files in c++
Files in c++Files in c++
Files in c++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
file handling c++
file handling c++file handling c++
file handling c++
 
String functions in C
String functions in CString functions in C
String functions in C
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Array in c
Array in cArray in c
Array in c
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Structure in C
Structure in CStructure in C
Structure in C
 
user defined function
user defined functionuser defined function
user defined function
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 

Andere mochten auch (20)

File Pointers
File PointersFile Pointers
File Pointers
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
C++ io manipulation
C++ io manipulationC++ io manipulation
C++ io manipulation
 
C++ file
C++ fileC++ file
C++ file
 
14 file handling
14 file handling14 file handling
14 file handling
 
File handling
File handlingFile handling
File handling
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
8 header files
8 header files8 header files
8 header files
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
Книга рецептов для пароконвектоматов ПКА серии ПП2 торговой марки Abat
Книга рецептов для пароконвектоматов ПКА серии ПП2 торговой марки AbatКнига рецептов для пароконвектоматов ПКА серии ПП2 торговой марки Abat
Книга рецептов для пароконвектоматов ПКА серии ПП2 торговой марки Abat
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Cohesion and coupling
Cohesion and couplingCohesion and coupling
Cohesion and coupling
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
 
Abat Combi-Steamers - Russian Brochure
Abat Combi-Steamers - Russian BrochureAbat Combi-Steamers - Russian Brochure
Abat Combi-Steamers - Russian Brochure
 

Ähnlich wie Files in c++ ppt

Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptxVishuSaini22
 
file management functions
file management functionsfile management functions
file management functionsvaani pathak
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-fileDeepak Singh
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handlingsparkishpearl
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Files in c
Files in cFiles in c
Files in cTanujaA3
 
Csc1100 lecture15 ch09
Csc1100 lecture15 ch09Csc1100 lecture15 ch09
Csc1100 lecture15 ch09IIUM
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfstudy material
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfaquacare2008
 

Ähnlich wie Files in c++ ppt (20)

Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
File management in C++
File management in C++File management in C++
File management in C++
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
file management functions
file management functionsfile management functions
file management functions
 
Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-file
 
Exmaples of file handling
Exmaples of file handlingExmaples of file handling
Exmaples of file handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Files in c
Files in cFiles in c
Files in c
 
Csc1100 lecture15 ch09
Csc1100 lecture15 ch09Csc1100 lecture15 ch09
Csc1100 lecture15 ch09
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File management
File managementFile management
File management
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 

Mehr von Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

Mehr von Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Kürzlich hochgeladen

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 

Kürzlich hochgeladen (20)

4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 

Files in c++ ppt

  • 1. Chapter 12 – File Operations 1 Starting Out with C++, 3rd Edition
  • 2. 12.1 What is a File? • A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused. 2 Starting Out with C++, 3rd Edition
  • 3. 12.2 File Names • All files are assigned a name that is used for identification purposes by the operating system and the user. 3 Starting Out with C++, 3rd Edition
  • 4. Table 12-1 File Name and Extension File Contents M Y P R O G .B A S BASIC program M E N U .B A T DOS Batch File I N S T A L L .D O C Documentation File C R U N C H .E X E Executable File B O B .H T M L HTML (Hypertext Markup Language) File 3 D M O D E L .J A V A Java program or applet I N V E N T .O B J Object File P R O G 1 .P R J Borland C++ Project File A N S I .S Y S System Device Driver R E A D M E .T X T Text File 4 Starting Out with C++, 3rd Edition
  • 5. 12.3 Focus on Software Engineering: The Process of Using a File • Using a file in a program is a simple threestep process – The file must be opened. If the file does not yet exits, opening it means creating it. – Information is then saved to the file, read from the file, or both. – When the program is finished using the file, the file must be closed. 5 Starting Out with C++, 3rd Edition
  • 6. Figure 12-1 6 Starting Out with C++, 3rd Edition
  • 7. Figure 12-2 7 Starting Out with C++, 3rd Edition
  • 8. 12.4 Setting Up a Program for File Input/Output • Before file I/O can be performed, a C++ program must be set up properly. • File access requires the inclusion of fstream.h 8 Starting Out with C++, 3rd Edition
  • 9. 12.5 Opening a File • Before data can be written to or read from a file, the file must be opened. ifstream inputFile; inputFile.open(“customer.dat”); 9 Starting Out with C++, 3rd Edition
  • 10. Program 12-1 // This program demonstrates the declaration of an fstream // object and the opening of a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; // Declare file stream object char fileName[81]; cout << "Enter the name of a file you wish to openn"; cout << "or create: "; cin.getline(fileName, 81); dataFile.open(fileName, ios::out); cout << "The file " << fileName << " was opened.n"; } 10 Starting Out with C++, 3rd Edition
  • 11. Program Output with Example Input Enter the name of a file you wish to open or create: mystuff.dat [Enter] The file mystuff.dat was opened. 11 Starting Out with C++, 3rd Edition
  • 12. Table 12-3 File Type Default Open Mode o fs tre a m The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted (the file is truncated). ifs tre a m The file is opened for input only. (Information may be read from the file, but not written to it.) The file’s contents will be read from its beginning. If the file does not exist, the open function fails. 12 Starting Out with C++, 3rd Edition
  • 13. Table 12-4 File Mode Flag Meaning io s ::a p p Append mode. If the file already exists, its contents are preserved and all output is written to the end of the file. By default, this flag causes the file to be created if it does not exist. io s ::a te If the file already exists, the program goes directly to the end of it. Output may be written anywhere in the file. io s ::b in a ry Binary mode. When a file is opened in binary mode, information is written to or read from it in pure binary format. (The default mode is text.) io s ::in Input mode. Information will be read from the file. If the file does not exist, it will not be created and the open function will fail. 13 Starting Out with C++, 3rd Edition
  • 14. Table 12-4 continued File Mode Flag Meaning io s ::n o c re a te If the file does not already exist, this flag will cause the open function to fail. (The file will not be created.) io s ::n o re p la c e If the file already exists, this flag will cause the open function to fail. (The existing file will not be opened.) io s ::o u t Output mode. Information will be written to the file. By default, the file’s contents will be deleted if it already exists. io s ::tru n c If the file already exists, its contents will be deleted (truncated). This is the default mode used by io s ::o u t. 14 Starting Out with C++, 3rd Edition
  • 15. Opening a File at Declaration fstream dataFile(“names.dat”, ios::in | ios::out); 15 Starting Out with C++, 3rd Edition
  • 16. Program 12-2 // This program demonstrates the opening of a file at the // time the file stream object is declared. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("names.dat", ios::in | ios::out); cout << "The file names.dat was opened.n"; } 16 Starting Out with C++, 3rd Edition
  • 17. Program Output with Example Input The file names.dat was opened. 17 Starting Out with C++, 3rd Edition
  • 18. Testing for Open Errors dataFile.open(“cust.dat”, ios::in); if (!dataFile) { cout << “Error opening file.n”; } 18 Starting Out with C++, 3rd Edition
  • 19. Another way to Test for Open Errors dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.n”; } 19 Starting Out with C++, 3rd Edition
  • 20. 12.6 Closing a File • A file should be closed when a program is finished using it. 20 Starting Out with C++, 3rd Edition
  • 21. Program 12-3 // This program demonstrates the close function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; dataFile.open("testfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File was created successfully.n"; cout << "Now closing the file.n"; dataFile.close(); } 21 Starting Out with C++, 3rd Edition
  • 22. Program Output File was created successfully. Now closing the file. 22 Starting Out with C++, 3rd Edition
  • 23. 12.7 Using << to Write Information to a File • The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !” 23 Starting Out with C++, 3rd Edition
  • 24. Program 12-4 // This program uses the << operator to write information to a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char line[81]; dataFile.open("demofile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } 24 Starting Out with C++, 3rd Edition
  • 25. Program continues cout << "File opened successfully.n"; cout << "Now writing information to the file.n"; dataFile << "Jonesn"; dataFile << "Smithn"; dataFile << "Willisn"; dataFile << "Davisn"; dataFile.close(); cout << "Done.n"; } 25 Starting Out with C++, 3rd Edition
  • 26. Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File demofile.txt Jones Smith Willis Davis 26 Starting Out with C++, 3rd Edition
  • 27. Figure 12-3 27 Starting Out with C++, 3rd Edition
  • 28. Program 12-5 // This program writes information to a file, closes the file, // then reopens it and appends more information. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; } dataFile.open("demofile.txt", ios::out); dataFile << "Jonesn"; dataFile << "Smithn"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willisn"; dataFile << "Davisn"; dataFile.close(); 28 Starting Out with C++, 3rd Edition
  • 29. Output to File demofile.txt Jones Smith Willis Davis 29 Starting Out with C++, 3rd Edition
  • 30. 12.8 File Output Formatting • File output may be formatted the same way as screen output. 30 Starting Out with C++, 3rd Edition
  • 31. Program 12-6 // This program uses the precision member function of a // file stream object to format file output. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; float num = 123.456; dataFile.open("numfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } 31 Starting Out with C++, 3rd Edition
  • 32. Program continues dataFile << num << endl; dataFile.precision(5); dataFile << num << endl; dataFile.precision(4); dataFile << num << endl; dataFile.precision(3); dataFile << num << endl; } 32 Starting Out with C++, 3rd Edition
  • 33. Contents of File numfile.txt 123.456 123.46 123.5 124 33 Starting Out with C++, 3rd Edition
  • 34. Program 12-7 #include <iostream.h> #include <fstream.h> #include <iomanip.h> void main(void) { fstream outFile("table.txt", ios::out); int nums[3][3] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 }; // Write the three rows of numbers for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { outFile << setw(4) << nums[row][col] << " "; } outFile << endl; } outFile.close(); } 34 Starting Out with C++, 3rd Edition
  • 35. Contents of File TABLE.TXT 2897 5 837 34 7 1623 390 3456 12 35 Starting Out with C++, 3rd Edition
  • 36. Figure 12-6 36 Starting Out with C++, 3rd Edition
  • 37. 12.9 Using >> to Read Information from a File • The stream extraction operator (>>) may be used to read information from a file. 37 Starting Out with C++, 3rd Edition
  • 38. Program 12-8 // This program uses the >> operator to read information from a file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.n"; cout << "Now reading information from the file.nn"; 38 Starting Out with C++, 3rd Edition
  • 39. Program continues for (int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close(); cout << "nDone.n"; } 39 Starting Out with C++, 3rd Edition
  • 40. Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done. 40 Starting Out with C++, 3rd Edition
  • 41. 12.10 Detecting the End of a File • The eof() member function reports when the end of a file has been encountered. if (inFile.eof()) inFile.close(); 41 Starting Out with C++, 3rd Edition
  • 42. Program 12-9 // This program uses the file stream object's eof() member // function to detect the end of the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.n"; cout << "Now reading information from the file.nn"; 42 Starting Out with C++, 3rd Edition
  • 43. Program continues dataFile >> name; // Read first name from the file while (!dataFile.eof()) { cout << name << endl; dataFile >> name; } dataFile.close(); cout << "nDone.n"; } 43 Starting Out with C++, 3rd Edition
  • 44. Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done. 44 Starting Out with C++, 3rd Edition
  • 45. Note on eof() • In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read. 45 Starting Out with C++, 3rd Edition
  • 46. 12.11 Passing File Stream Objects to Functions • File stream objects may be passed by reference to functions. bool openFileIn(fstream &file, char name[51]) { bool status; file.open(name, ios::in); if (file.fail()) status = false; else status = true; return status; } 46 Starting Out with C++, 3rd Edition
  • 47. 12.12 More Detailed Error Testing • All stream objects have error state bits that indicate the condition of the stream. 47 Starting Out with C++, 3rd Edition
  • 48. Table 12-5 Bit Description io s ::e o fb it Set when the end of an input stream is encountered. Set when an attempted operation has failed. Set when an unrecoverable error has occurred. Set when an invalid operation has been attempted. Set when all the flags above are not set. Indicates the stream is in good condition. io s ::fa ilb it io s ::h a rd fa il io s ::b a d b it io s ::g o o d b it 48 Starting Out with C++, 3rd Edition
  • 49. Table 12-6 Function Description e o f() Returns true (non-zero) if the eofbit flag is set, otherwise returns false. Returns true (non-zero) if the failbit or hardfail flags are set, otherwise returns false. Returns true (non-zero) if the badbit flag is set, otherwise returns false. Returns true (non-zero) if the goodbit flag is set, otherwise returns false. When called with no arguments, clears all the flags listed above. Can also be called with a specific flag as an argument. fa il() b a d () g o o d () c le a r() 49 Starting Out with C++, 3rd Edition
  • 50. Program 12-11 // This program demonstrates the return value of the stream // object error testing member functions. #include <iostream.h> #include <fstream.h> // Function prototype void showState(fstream &); void main(void) { fstream testFile("stuff.dat", ios::out); if (testFile.fail()) { cout << "cannot open the file.n"; return; } 50 Starting Out with C++, 3rd Edition
  • 51. Program continues int num = 10; cout << "Writing to the file.n"; testFile << num; // Write the integer to testFile showState(testFile); testFile.close(); // Close the file testFile.open("stuff.dat", ios::in); // Open for input if (testFile.fail()) { cout << "cannot open the file.n"; return; } 51 Starting Out with C++, 3rd Edition
  • 52. Program continues } cout << "Reading from the file.n"; testFile >> num; // Read the only number in the file showState(testFile); cout << "Forcing a bad read operation.n"; testFile >> num; // Force an invalid read operation showState(testFile); testFile.close(); // Close the file // Definition of function ShowState. This function uses // an fstream reference as its parameter. The return values of // the eof(), fail(), bad(), and good() member functions are // displayed. The clear() function is called before the function // returns. 52 Starting Out with C++, 3rd Edition
  • 53. Program continues void showState(fstream &file) { cout << "File Status:n"; cout << " eof bit: " << file.eof() << endl; cout << " fail bit: " << file.fail() << endl; cout << " bad bit: " << file.bad() << endl; cout << " good bit: " << file.good() << endl; file.clear(); // Clear any bad bits } 53 Starting Out with C++, 3rd Edition
  • 54. Program Output Writing to the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Reading from the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Forcing a bad read operation. File Status: eof bit: 1 fail bit: 2 bad bit: 0 good bit: 0 54 Starting Out with C++, 3rd Edition
  • 55. 12.13 Member Functions for Reading and Writing Files • File stream objects have member functions for more specialized file reading and writing. 55 Starting Out with C++, 3rd Edition
  • 56. Figure 12-8 56 Starting Out with C++, 3rd Edition
  • 57. Program 12-12 // This program uses the file stream object's eof() member // function to detect the end of the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; } 57 Starting Out with C++, 3rd Edition
  • 58. Program 12-12 (continued) nameFile >> input; while (!nameFile.eof()) { cout << input; nameFile >> input; } nameFile.close(); } 58 Starting Out with C++, 3rd Edition
  • 60. The getline Member Function • dataFile.getline(str, 81, ‘n’); str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘n’ is the default.) 60 Starting Out with C++, 3rd Edition
  • 61. Program 12-13 // This program uses the file stream object's getline member // function to read a line of information from the file. #include <iostream.h> #include <fstream.h> void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; } 61 Starting Out with C++, 3rd Edition
  • 62. Program continues nameFile.getline(input, 81); // use n as a delimiter while (!nameFile.eof()) { cout << input << endl; nameFile.getline(input, 81); // use n as a delimiter } nameFile.close(); } 62 Starting Out with C++, 3rd Edition
  • 63. Program Screen Output Jayne Murphy 47 Jones Circle Almond, NC 28702 63 Starting Out with C++, 3rd Edition
  • 64. Program 12-14 // This file shows the getline function with a user// specified delimiter. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("names2.txt", ios::in); char input[81]; dataFile.getline(input, 81, '$'); while (!dataFile.eof()) { cout << input << endl; dataFile.getline(input, 81, '$'); } dataFile.close(); } 64 Starting Out with C++, 3rd Edition
  • 65. Program Output Jayne Murphy 47 Jones Circle Almond, NC 28702 Bobbie Smith 217 Halifax Drive Canton, NC 28716 Bill Hammet PO Box 121 Springfield, NC 28357 65 Starting Out with C++, 3rd Edition
  • 66. The get Member Function inFile.get(ch); 66 Starting Out with C++, 3rd Edition
  • 67. Program 12-15 // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include <iostream.h> #include <fstream.h> void main(void) { fstream file; char ch, fileName[51]; cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) { cout << fileName << “ could not be opened.n"; return; } 67 Starting Out with C++, 3rd Edition
  • 68. Program continues file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close(); } 68 Starting Out with C++, 3rd Edition
  • 69. The put Member Function • outFile.put(ch); 69 Starting Out with C++, 3rd Edition
  • 70. Program 12-16 // This program demonstrates the put member function. #include <iostream.h> #include <fstream.h> void main(void) { fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } dataFile.close(); } 70 Starting Out with C++, 3rd Edition
  • 71. Program Screen Output with Example Input Type a sentence and be sure to end it with a period. I am on my way to becoming a great programmer. [Enter] Resulting Contents of the File SENTENCE.TXT: I am on my way to becoming a great programmer. 71 Starting Out with C++, 3rd Edition
  • 72. 12.14 Focus on Software Engineering: Working with Multiple Files • It’s possible to have more than one file open at once in a program. 72 Starting Out with C++, 3rd Edition
  • 73. Program 12-17 // This program demonstrates reading from one file and writing // to a second file. #include <iostream.h> #include <fstream.h> #include <ctype.h> // Needed for the toupper function void main(void) { ifstream inFile; ofstream outFile("out.txt"); char fileName[81], ch, ch2; cout << "Enter a file name: "; cin >> fileName; inFile.open(fileName); if (!inFile) { cout << "Cannot open " << fileName << endl; return; } 73 Starting Out with C++, 3rd Edition
  • 74. Program continues inFile.get(ch); // Get a characer from file 1 while (!inFile.eof()) // Test for end of file { ch2 = toupper(ch); // Convert to uppercase outFile.put(ch2); // Write to file2 inFile.get(ch); // Get another character from file 1 } inFile.close(); outFile.close(); cout << "File conversion done.n"; } 74 Starting Out with C++, 3rd Edition
  • 75. Program Screen Output with Example Input Enter a file name: hownow.txt [Enter] File conversion done. Contents of hownow.txt: how now brown cow. How Now? Resulting Contents of out.txt: HOW NOW BROWN COW. HOW NOW? 75 Starting Out with C++, 3rd Edition
  • 76. 12.15 Binary Files • Binary files contain data that is unformatted, and not necessarily stored as ASCII text. file.open(“stuff.dat”, ios::out | ios::binary); 76 Starting Out with C++, 3rd Edition
  • 77. Figure 12-9 77 Starting Out with C++, 3rd Edition
  • 78. Figure 12-10 78 Starting Out with C++, 3rd Edition
  • 79. Program 12-18 // This program uses the write and read functions. #include <iostream.h> #include <fstream.h> void main(void) { fstream file(“NUMS.DAT", ios::out | ios::binary); int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Now writing the data to the file.n"; file.write((char*)buffer, sizeof(buffer)); file.close(); file.open("NUMS.DAT", ios::in); // Reopen the file. cout << "Now reading the data back into memory.n"; file.read((char*)buffer, sizeof(buffer)); for (int count = 0; count < 10; count++) cout << buffer[count] << " "; file.close(); } 79 Starting Out with C++, 3rd Edition
  • 80. Program Screen Output Now writing the data to the file. Now reading the data back into memory. 1 2 3 4 5 6 7 8 9 10 80 Starting Out with C++, 3rd Edition
  • 81. 12.16 Creating Records with Structures • Structures may be used to store fixed-length records to a file. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; }; • Since structures can contain a mixture of data types, you should always use the ios::binary mode when opening a file to store them. 81 Starting Out with C++, 3rd Edition
  • 82. Program 12-19 // This program demonstrates the use of a structure variable to // store a record of information to a file. #include <iostream.h> #include <fstream.h> #include <ctype.h> // for toupper // Declare a structure for the record. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; }; 82 Starting Out with C++, 3rd Edition
  • 83. Program continues void main(void) { fstream people("people.dat", ios::out | ios::binary); Info person; char again; if (!people) { cout << "Error opening file. Program aborting.n"; return; } do { cout << "Enter the following information about a ” << "person:n"; cout << "Name: "; 83 Starting Out with C++, 3rd Edition
  • 84. Program continues cin.getline(person.name, 51); cout << "Age: "; cin >> person.age; cin.ignore(); // skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, 51); cout << "Address line 2: "; cin.getline(person.address2, 51); cout << "Phone: "; cin.getline(person.phone, 14); people.write((char *)&person, sizeof(person)); cout << "Do you want to enter another record? "; cin >> again; cin.ignore(); } while (toupper(again) == 'Y'); people.close(); } 84 Starting Out with C++, 3rd Edition
  • 85. Program Screen Output with Example Input Enter the following information about a person: Name: Charlie Baxter [Enter] Age: 42 [Enter] Address line 1: 67 Kennedy Bvd. [Enter] Address line 2: Perth, SC 38754 [Enter] Phone: (803)555-1234 [Enter] Do you want to enter another record? Y [Enter] Enter the following information about a person: Name: Merideth Murney [Enter] Age: 22 [Enter] Address line 1: 487 Lindsay Lane [Enter] Address line 2: Hazelwood, NC 28737 [Enter] Phone: (704)453-9999 [Enter] Do you want to enter another record? N [Enter] 85 Starting Out with C++, 3rd Edition
  • 86. 12.17 Random Access Files • Random Access means non-sequentially accessing informaiton in a file. Figure 12-11 86 Starting Out with C++, 3rd Edition
  • 87. Table 12-7 Mode Flag Description io s ::b e g The offset is calculated from the beginning of the file. io s ::e n d The offset is calculated from the end of the file. io s ::c u r The offset is calculated from the current position. 87 Starting Out with C++, 3rd Edition
  • 88. Table 12-8 Statement How it Affects the Read/Write Position F ile .s e e k p ( 3 2 L , io s ::b e g ) ; Sets the write position to the 33rd byte (byte 32) from the beginning of the file. file .s e e k p ( - 1 0 L , io s ::e n d ) ; Sets the write position to the 11th byte (byte 10) from the end of the file. file .s e e k p ( 1 2 0 L , io s ::c u r ) ; Sets the write position to the 121st byte (byte 120) from the current position. file .s e e k g ( 2 L , io s ::b e g ) ; Sets the read position to the 3rd byte (byte 2) from the beginning of the file. file .s e e k g ( - 1 0 0 L , io s ::e n d ) ; Sets the read position to the 101st byte (byte 100) from the end of the file. file .s e e k g ( 4 0 L , io s ::c u r ) ; Sets the read position to the 41st byte (byte 40) from the current position. file .s e e k g ( 0 L , io s ::e n d ) ; Sets the read position to the end of the file. 88 Starting Out with C++, 3rd Edition
  • 89. Program 12-21 // This program demonstrates the seekg function. #include <iostream.h> #include <fstream.h> void main(void) { fstream file("letters.txt", ios::in); char ch; file.seekg(5L, ios::beg); file.get(ch); cout << "Byte 5 from beginning: " << ch << endl; file.seekg(-10L, ios::end); file.get(ch); cout << "Byte 10 from end: " << ch << endl; 89 Starting Out with C++, 3rd Edition
  • 90. Program continues file.seekg(3L, ios::cur); file.get(ch); cout << "Byte 3 from current: " << ch << endl; file.close(); } 90 Starting Out with C++, 3rd Edition
  • 91. Program Screen Output Byte 5 from beginning: f Byte 10 from end: q Byte 3 from current: u 91 Starting Out with C++, 3rd Edition
  • 92. The tellp and tellg Member Functions • tellp returns a long integer that is the current byte number of the file’s write position. • tellg returns a long integer that is the current byte number of the file’s read position. 92 Starting Out with C++, 3rd Edition
  • 93. Program 12-23 // This program demonstrates the tellg function. #include <iostream.h> #include <fstream.h> #include <ctype.h> // For toupper void main(void) { fstream file("letters.txt", ios::in); long offset; char ch, again; do { cout << "Currently at position " << file.tellg() << endl; cout << "Enter an offset from the beginning of the file: "; cin >> offset; 93 Starting Out with C++, 3rd Edition
  • 94. Program continues file.seekg(offset, ios::beg); file.get(ch); cout << "Character read: " << ch << endl; cout << "Do it again? "; cin >> again; } while (toupper(again) == 'Y'); file.close(); } 94 Starting Out with C++, 3rd Edition
  • 95. Program Output with Example Input Currently at position 0 Enter an offset from the beginning of the file: 5 [Enter] Character read: f Do it again? y [Enter] Currently at position 6 Enter an offset from the beginning of the file: 0 [Enter] Character read: a Do it again? y [Enter] Currently at position 1 Enter an offset from the beginning of the file: 20 [Enter] Character read: u Do it again? n [Enter] 95 Starting Out with C++, 3rd Edition
  • 96. 12.18 Opening a File for Both Input and Output • You may perform input and output on an fstream file without closing it and reopening it. fstream file(“data.dat”, ios::in | ios::out); 96 Starting Out with C++, 3rd Edition
  • 97. Program 12-24 // This program sets up a file of blank inventory records. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::out | ios::binary); Invtry record = { "", 0, 0.0 }; 97 Starting Out with C++, 3rd Edition
  • 98. Program continues // Now write the blank records for (int count = 0; count < 5; count++) { cout << "Now writing record " << count << endl; inventory.write((char *)&record, sizeof(record)); } inventory.close(); } 98 Starting Out with C++, 3rd Edition
  • 100. Program 12-25 // This program displays the contents of the inventory file. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::in | ios::binary); Invtry record = { "", 0, 0.0 }; 100 Starting Out with C++, 3rd Edition
  • 101. Program continues // Now read and display the records inventory.read((char *)&record, sizeof(record)); while (!inventory.eof()) { cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl << endl; inventory.read((char *)&record, sizeof(record)); } inventory.close(); } 101 Starting Out with C++, 3rd Edition
  • 102. Here is the screen output of Program 12-25 if it is run immediately after Program 12-24 sets up the file of blank records. Program Screen Output Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 102 Starting Out with C++, 3rd Edition
  • 103. Program 12-26 // This program allows the user to edit a specific record in // the inventory file. #include <iostream.h> #include <fstream.h> // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { 103 Starting Out with C++, 3rd Edition
  • 104. Program continues fstream inventory("invtry.dat", ios::in | ios::out | Invtry record; long recNum; cout << "Which record do you want to edit?"; cin >> recNum; inventory.seekg(recNum * sizeof(record), ios::beg); inventory.read((char *)&record, sizeof(record)); cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl; cout << "Enter the new data:n"; cout << "Description: "; ios::binary); 104 Starting Out with C++, 3rd Edition
  • 105. Program continues cin.ignore(); cin.getline(record.desc, 31); cout << "Quantity: "; cin >> record.qty; cout << "Price: "; cin >> record.price; inventory.seekp(recNum * sizeof(record), ios::beg); inventory.write((char *)&record, sizeof(record)); inventory.close(); } 105 Starting Out with C++, 3rd Edition
  • 106. Program Screen Output with Example Input Which record do you ant to edit? 2 [Enter] Description: Quantity: 0 Price: 0.0 Enter the new data: Description: Wrench [Enter] Quantity: 10 [Enter] Price: 4.67 [Enter] 106 Starting Out with C++, 3rd Edition