Sunteți pe pagina 1din 21

FILE PROCESSING

CHAPTER 9
ICT1103 Structured Programming
Topics

• Sequential Access Files


• Random Access Files

 2000 Prentice Hall, Inc.


2
All rights reserved.
Introduction
■ Data files
– Can be created, updated, and processed
– Are used for permanent storage of large amounts of
data
■ Storage of data in variables and arrays is only temporary

 2000 Prentice Hall, Inc.


3
All rights reserved.
Files and Streams
■ Read/Write functions in standard library
– fgetc
■ Reads one character from a file
■ Takes a FILE pointer as an argument
■ fgetc( stdin ) equivalent to getchar()
– fputc
■ Writes one character to a file
■ Takes a FILE pointer and a character to write as an argument
■ fputc( 'a', stdout ) equivalent to putchar( 'a' )
– fgets
■ Reads a line from a file
– fputs
■ Writes a line to a file
– fscanf / fprintf
■ File processing equivalents of scanf and printf
 2000 Prentice Hall, Inc.
4
All rights reserved.
Creating a Sequential Access File
■ Creating a File
– FILE *myPtr;
■ Creates a FILE pointer called myPtr
– myPtr = fopen("myFile.dat", openmode);
■ Function fopen returns a FILE pointer to file specified
■ Takes two arguments – file to open and file open mode
■ If open fails, NULL returned
– fprintf
■ Used to print to a file
■ Like printf, except first argument is a FILE pointer (pointer
to the file you want to print in)

 2000 Prentice Hall, Inc.


5
All rights reserved.
Creating a Sequential Access File
– feof( FILE pointer )
■ Returns true if end-of-file indicator (no more data to
process) is set for the specified file
– fclose( FILE pointer )
■ Closes specified file
■ Performed automatically when program ends
■ Good practice to close files explicitly
■ Details
– Programs may process no files, one file, or many files
– Each file must have a unique name and should have its
own pointer

 2000 Prentice Hall, Inc.


6
All rights reserved.
Using the fstream Data Type
■ Table of file open modes:

Mod e Desc rip tion


r Open a file for reading.
w Create a file for writing. If the file already exists,
discard the current contents.
a Append; open or create a file for writing at end of file.
r+ Open a file for update (reading and writing).
w+ Create a file for update. If the file already exists,
discard the current contents.
a+ Append; open or create a file for update; writing is
done at the end of the file.

 2000 Prentice Hall, Inc.


7
All rights reserved.
Creating a Sequential Access File
C++ provides the following classes to perform output and input of
characters to/from files:

■ ofstream: Stream class to write on files


■ ifstream: Stream class to read from files
■ fstream: Stream class to both read and write from/to files.

 2000 Prentice Hall, Inc.


8
All rights reserved.
Using the fstream Data
Type
■ These classes are derived directly or indirectly from the
classes istream and ostream. We have already used
objects whose types were these classes: cin is an object of
class istream and cout is an object of class ostream.
Therefore, we have already been using classes that are
related to our file streams. And in fact, we can use our file
streams the same way we are already used to use cin and
cout, with the only difference that we have to associate
these streams with physical files.

 2000 Prentice Hall, Inc.


9
All rights reserved.
Using the fstream Data
Type
int main()
{
fstream dataFile;
cout << "Opening file...\n";
dataFile.open("demofile.txt",ios::out);//open for output

cout << "Now writing the data to the file" << endl;
dataFile << "Jonas\n";
dataFile << "Smith\n";
dataFile << "Willis\n";
dataFile << "Davis\n";

cout << "Done." << endl;

return 0;
}

 2000 Prentice Hall, Inc.


All rights 10
reserved.
File Output Formatting
■ setprecision and fixed manipulators may be called to establish the
number of digits of precision that floating point values are rounded to.

 2000 Prentice Hall, Inc.


All rights 11
reserved.
File Output Formatting
int main()
{
fstream dataFile;
double num = 17.816392;
dataFile.open("numfile.txt");
dataFile << fixed;
dataFile << num << endl;
dataFile << setprecision(4);
dataFile << num << endl;
dataFile << setprecision(2);
dataFile << num << endl;
cout << "Done.\n";
dataFile.close();
return 0;
 2000 Prentice Hall, Inc.
} All rights 12
reserved.
The getline() function
int main()
{
string input;
fstream nameFile;

nameFile.open("murphy.txt", ios::in);//open file in input mode

if (nameFile)
{
getline(nameFile, input);//read item from the file

while (nameFile)
{
cout << input << endl;
getline(nameFile, input);
}
nameFile.close();
}
else
{
cout << "ERROR:Cannot open file\n";
}
return 0;
}  2000 Prentice Hall, Inc.
All rights 13
reserved.
The get() function
■ It reads a single character from the file.
int main()
{
string fileName;
char ch;
fstream file;
cout << "Enter a file name:";
cin >>fileName;
file.open(fileName, ios::in);
if (file)//if filename successfully open
{
file.get(ch);
while (file)
{cout << ch;
file.get(ch);}
file.close();
}
else
{cout << fileName << " could not be opened.\n“;}
return 0;
 2000 Prentice Hall, Inc.
}
All rights 14
reserved.
The put() function
■ The put member function writes a single character to the file.

int main()
{
char ch;
fstream dataFile("sentence.txt");
cout << "Type a sentence and be sure to end it with a period.\n";
cin.get(ch);
while (ch != '.')
{
dataFile.put(ch);
cin.get(ch);
}
dataFile.put(ch);
dataFile.close();
return 0;
}

 2000 Prentice Hall, Inc.


All rights 15
reserved.
Random Access Files

■ Random file access -- Skip around to various points in the file


to read its contents.
■ Can be useful when your file is full of records, and you wish to
retrieve a specific record.
■ Random file access is done by manipulating the file pointer
using either seekg() function (for input) and seekp()
function (for output).

 2000 Prentice Hall, Inc.


All rights 16
reserved.
Random Access Files

■ The seekg() and seekp() functions take two


parameters. The first parameter is an offset that determines
how many bytes to move the file pointer. The second
parameter is an Ios flag that specifies what the offset
parameter should be offset from.
■ A positive offset means move the file pointer towards the end
of the file, whereas a negative offset means move the file
pointer towards the beginning of the file.

 2000 Prentice Hall, Inc.


All rights 17
reserved.
Random Access Files

■ Example:
Sample.dat
This is line 1
This is line 2
This is line 3
This is line 4

 2000 Prentice Hall, Inc.


All rights 18
reserved.
Random Access Files
1
2
3
int main()
4
5
6
{
7
8
9
using namespace std;
10
11
12
ifstream inf("Sample.dat");
13
14
15
16
17
18
// If we couldn't open the input file stream for reading
19
20
21
if (!inf)
22
23
24
{
25
26
27
// Print an error and exit
28
29
30
cerr << "Uh oh, Sample.dat could not be opened for reading!" << endl;
31
32
33
exit(1);
}
string strData;
inf.seekg(5); // move to 5th character
// Get the rest of the line and print it
getline(inf, strData);
cout << strData << endl;

inf.seekg(8, ios::cur); // move 8 more bytes into file


// Get rest of the line and print it
getline(inf, strData);
cout << strData << endl;

inf.seekg(-15, ios::end); // move 15 bytes before end of file


// Get rest of the line and print it
getline(inf, strData);
cout << strData << endl;
return 0;  2000 Prentice Hall, Inc.
} All rights 19
reserved.
Random Access Files
■ Output:

is line 1
line 2
his is line 4

 2000 Prentice Hall, Inc.


All rights 20
reserved.
■ End Part A

 2000 Prentice Hall, Inc.


All rights 21
reserved.

S-ar putea să vă placă și