Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
562 views

File Processing in C++

The document discusses file processing in C++. It covers opening, reading from, and writing to both sequential and random access files. The key steps are: 1) Open the file using ifstream, ofstream, or fstream objects; 2) Read from or write to the file using stream extraction (>>) and insertion (<<) operators; 3) Close the file stream when complete. Random access files allow non-sequential access using seek functions like seekg() and seekp().

Uploaded by

Dilshan Sudaraka
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
562 views

File Processing in C++

The document discusses file processing in C++. It covers opening, reading from, and writing to both sequential and random access files. The key steps are: 1) Open the file using ifstream, ofstream, or fstream objects; 2) Read from or write to the file using stream extraction (>>) and insertion (<<) operators; 3) Close the file stream when complete. Random access files allow non-sequential access using seek functions like seekg() and seekp().

Uploaded by

Dilshan Sudaraka
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Introduction

File Processing

A computer file
is stored on a secondary storage device (e.g., hard disk, USB pen); is permanent; can be used to provide input data to a program or receive output data from a program, or both; must be opened before it is used.

General File I/O Steps


Open the file. Use the file.
Read from the file or Write to the file or Both

Types of Files
Two types of files.
Sequential files Random access files

Sequential files
The values only can be accessed in the same sequence in which they are stored. To use we must move through successive data items in the same order as they stored in the disk.

Close the file.

Random access files


Values can be accessed in any order desired by the programmer.

Using Input/Output Files


stream - a sequence of characters
interactive (iostream)
cin - input stream associated keyboard. cout - output associated with display.

Stream I/O Library Header Files


Note - There is no .h on standard header files: <fstream> iostream - contains basic infon required for all stream I/O operations. iomanip - contains information useful for performing formatted I/O with parameterized stream manipulators. fstream - contains information for performing file I/O operations.

file (fstream)
ifstream - defines new input stream (normally associated with a file). ofstream - defines new output stream (normally associated with a file).

Classes for Stream I/O in C++


int main () { ifstream fin; ofstream fout;

C++ Streams
#include <fstream> File fin Memory

fin is an input instance of ifstream

ios is the base classs. istream and ostream inherit from ios. ifstream inherits from istream (and ios) ofstream inherits from ostream (and ios). iostream inherits from istream and ostream (and ios). fstream inherits from ifstram, iostream and ofstream.

return 0; } File fout Memory

fout is an output instance of ofstream

Opening a File
Files are opened by creating objects of stream classes.
ifstream for input ofstream for output fstream for input/output

Using the Constructor


First select the required stream.
ifstream for reading data from a file to the memory. ofstream for writing data from the memory to a file. fstream for both reading and writing data from a file to the memory and vice versa.

And then connecting to a disk file.


Two methods
Using the constructor Using the open method.

Declare a variable of the selected stream and pass the disk file name as the argument.
E.g., ifstream fin (MyFile.dat);

Using the open() Method


Select the required stream. Declare a variable of that stream.
E.g., ofstream fout;

Open () Method Successful?


Remember to check open() method is successful before using the file in your program.
ofstream fout; fout.open (My_File.txt"); if (fout.fail ()) { cout << "Failed to open the file\n"; exit (1); } else { // File processing } fout.close ();

Connect the stream to a disk file using the member function open() with the argument as the disk file name.
E.g., fout.open (OutFile.txt);

Writing to a File
Use the ofstream object (say fout) to send output to the disk file just like you send output to the screen by using cout.
ofstream fout (ouput.dat); float avgSales; fout << Hello there!!\n; // Writing a message to the file output.dat fout << avgSales; // Writing the contents of the variable avgSales fout.close (); // Close the file

Reading from a File


Use the ifstream object (say fin) to receive input from the disk file just like you use cin to get input from the keyboard. input.dat
ifstream fin (input.dat); string name; int age; fin >> name; // Reads Sunera into name fin >> age; // Reads 29 into age fin.close (); Sunera 29 Kundala 34

Closing the File


After process the file, close the streams using the method close(). fin.close (); // ifstream object fout.close (); // ofstream object

eof () Method
Useful when no of records stored in the file is unknown. Returns non-zero on end-of-file.

Example - Reading
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream fin; string name; int age; fin.open (input.dat"); if (fin.fail()) { cout << "Failed to open the file\n"; exit(1); } else { while (!fin.eof()){ fin >> name; fin >> age; cout << name << "\t" << age << "\n"; } } fin.close(); return (EXIT_SUCCESS); }

More File-Related Functions


fin.get (char & ch)
extracts next character from the input stream fin and places it in the character variable ch.

input.dat
Sunera Kundala Chathura Nayana Lalith 29 34 55 34 23

Output ?????? ...

ifstream & getline (ifstream & fin, string & str)


reads a line from the input stream fin and put it in the string str. E.g., getline (fin, line);

fout.put (char ch)


inserts character ch to the output stream fout.

Stream-state Methods
eof () non-zero on end-of-file. fail () non-zero if last I/O operation failed or invalid operation attempted or if theres been an unrecoverable error. bad () non-zero if invalid operation attempted or if theres been an unrecoverable error. good () non-zero if all stream state bits are zero.
Mode value ios::in ios::out ios::ate ios::app ios::trunc ios::nocreate

File Open Modes


Description open for reading. open for writing. seek (go) to the end of file at opening time. append mode: all writes occur at the end of file. truncate the file if it already exist. open fails if file does not exist. open fails if file already exists. open as a binary file.

ios::noreplace ios::binary

Appending Data to a File


#include <fstream> #include <iostream> using namespace std; int main() { ofstream fout; fout.open (data.txt", ios::app); if (fout.fail()){ cout << "Error: Cannot be opened\n"; exit (1); } fout << "Waranga\t" << 5 << "\n"; fout.close(); return (EXIT_SUCCESS); } data.txt before appending Sunera Kundala Chathura Nayana Lalith 29 34 55 34

Random Access Files


Function Member of the class Action Performed

23

seekg ()

ifstream

Moves get file pointer to a specific location

data.txt after appending Sunera Kundala Chathura Nayana Lalith Waranga 29 34 55 34 23 5

seekp ()

ofstream

Moves put file pointer to a specific location

tellg ()

ifstream

Returns the current position of the get pointer

tellp()

ofstream

Returns the current position of the put pointer

Prototypes of Seek Functions


istream & seekg (long offset, seekDir origin = ios::beg); ostream & seekp (long offset, seekDir origin = ios::beg); File seek origins
ios::beg seek from beginning of a file. ios::cur seek from the current location. ios::end seek from end of a file.

Examples
Positions to the 11th byte from the beginning
fin.seekg (10, ios::beg); or fin.seekg (10);

To get the size of the file


fin.seekg (0, ios::end); int size = fin.tellg ();

Seek Calls and Their Actions


Seek call
fin.seekg (0, ios::beg) fin.seekg (0, ios::cur) fin.seekg (0, ios:: end) fin.seekg (n, ios:: beg) fin.seekg (n, ios:: cur) fin.seekg(-n, ios::cur) fout.seekp(n, ios:: beg) fout.seekp(-n, ios:: cur)

Reading/Writing Functions for Binary Files

Action performed
Go to the beginning of the file Stay at the current position Go to the end of the file Move to (n+1) byte location in the file Move forward by n bytes from the current position Move backward by n bytes from current position Move write pointer to (n+1) byte location Move write pointer backward by n bytes

get () - read a byte and point to the next byte to read put () - write a byte and point to the next location for write read () - block reading write () - block writing

put () and get () Methods (1)


#include <fstream> #include <iostream> #include <string> using namespace std; int main() { fstream fio ("student.txt", ios::out|ios::in|ios::binary); char ch; string s; cout << "Enter a string: "; getline (cin, s); int len = s.length(); for (int i=0; i<len; i++){ ch = s[i]; fio.put(ch); // put the content of ch to the file }

put () and get () Methods (2)


cout << Stored string: "; fio.seekg(0, ios::beg); while (!fio.eof()){ fio.get(ch); // read one character cout << ch; } fio.close(); return (EXIT_SUCCESS); } Output??? Enter a string: All that glisters is not gold Stored string: All that glisters is not gold

write () and read () Methods


Access data in binary format.
fin.read ((char *) & variable, sizeof (variable)); fout.write ((char *) & variable, sizeof (variable));
int main() { ofstream fout ("numbers.txt", ios::binary); int num1 = 123; float num2 = 525.25; int i; float x; fout.write((char *) &num1, sizeof(num1)); fout.write((char *) &num2, sizeof(num2)); fout.close(); ifstream fin ("numbers.txt", ios::binary); fin.read((char *) &i, sizeof(i)); fin.read((char *) &x, sizeof(x)); fin.close(); cout << i << " " << x << "\n"; return (EXIT_SUCCESS); }

A Random Access File Example (1)


class Person { protected: static int id; string name; int age; public: Person () {} ~Person () { } friend ostream & operator << (ostream & out, const Person & p); friend istream & operator >> (istream & in, Person & p); friend ofstream & operator << (ofstream & fout, const Person & p); friend ifstream & operator >> (ifstream & fin, Person & p); }; int Person :: id;

output 123 525.25

A Random Access File Example (1)


ostream & operator << (ostream & out, const Person & p){ out << p.id << " " << p.name << " " << p.age; return (out); } istream & operator >> (istream & in, Person & p){ Person::id += 1; cout << "Name: "; in >> p.name; cout << "Age: "; in >> p.age; return (in); }

A Random Access File Example (1)


ofstream & operator << (ofstream & fout, const Person & p){ fout.seekp(0, ios::end); fout.write((char *) & p, sizeof(p)); return (fout); } ifstream & operator >> (ifstream & fin, Person & p) { int id_access; int location; cout << "Enter record ID: "; cin >> id_access; location = (id_access-1)*sizeof(p); fin.seekg(location, ios::beg); fin.read((char *) & p, sizeof(p)); return (fin); }

A Random Access File Example (1)


int main() { ofstream fout ("persons.txt", ios::binary); Person p; char ch; do{ cin >> p; fout << p; cout << "Another? "; cin >> ch; } while (toupper (ch) == 'Y'); fout.close(); ifstream fin ("persons.txt", ios::binary); fin >> p; cout << p; fin.close(); return (EXIT_SUCCESS); }

You might also like