Files-Functions and Operations (2)
Files-Functions and Operations (2)
2
How do we store data permanently ?
• Store data in secondary storage devices (floppy disk,
hard disk, tape, etc.).
• File input stream – Reads data from disk file to the program
• File output stream – Writes data to the disk file from the program
5
Files (Streams)
Input Stream - The source stream that provides data to the program.
Output Stream - The destination stream that receives output from the program.
Program
Output device
Insertion into
Output Stream output stream
6
Files (Streams)
The I/O system of C++ contains –
1. ifstream - Provides input operations on files (File
opened for input only. Information may be
read from the file but not written to it. If the
file does not exist, the open function fails).
2. ofstream - Provides output operations on files (File
opened for output only. Information may be
written to the file but not read from the file. If the
file does not exist, file is created. If the file is
already existed its contents are deleted).
3. fstream - Supports for simultaneous input and
output operations on files.
7
Flow of Data
Data
PROGRAM
Input
Stream Output
>> Stream
<<
DEVICE
(Extraction
OR (Insertion
operator)
operator)
Data FILES
8
File Types
1. Text files
– A text file can be a stream of characters that a computer can process
sequentially. It is not only processed sequentially but only in forward
direction. For this reason a text file is usually opened for only one kind of
operation (reading, writing, or appending) at any given time.
2. Binary files
– A binary file is no different to a text file. It is a collection of bytes. In C
Programming Language a byte and a character are equivalent. Hence a
binary file is also referred to as a character stream, but there are two
essential differences.
1. No special processing of the data occurs and each byte of data is
transferred to or from the disk unprocessed.
2. C Programming Language places no constructs on the file, and it may
be read from, or written to, in any manner chosen by the programmer.
– Binary files can be either processed sequentially or, depending on the needs
of the application, they can be processed using random access techniques.
• By default, C++ opens the files in text mode.
9
General File I/O steps
1. Declare a File name variable
2. Associate the file name variable with the disk
filename.
3. Open the file.
• Syntax
void open(const char *filename, ios::openmode mode);
• Here, the first argument specifies the name and location of the
file to be opened and the second argument of the open() member
function defines the mode in which the file should be opened.
11
Modes of a File
ios::ate Open a file for output and move the read/write control to the
end of the file.
ios::trunc If the file already exists, its contents will be truncated before
opening the file.
12
Modes of a File
We can combine two or more of these values by ORing them
together. For example if you want to open a file in write mode
and want to truncate it in case it already exists, following
• Similar way, you can open a file for reading and writing purpose
as follows:
– fstream appendfile;
– appendfile.open("file.dat", ios::out | ios::in ); .
13
Closing a File
• When a C++ program terminates it automatically closes flushes
all the streams, release all the allocated memory and close all the
opened files. But it is always a good practice that a programmer
should close all the opened files before program termination.
– void close();
Example - outfile.close()
14
Example
// This program demonstrates the opening of a file
#include <iostream>
#include <fstream.h>
using namespace std;
int main()
{ fstream dataFile("names.dat", ios::in | ios::out);
if (!dataFile) // file failed to open
cout << “Error opening file.\n”;
else
cout << "The file names.dat was opened.\n";
dataFile.close(); // file closed
return 0;
}
15
Reading or Writing data to/from file
Data Functions for reading file Function for writing into file
16
Program - Reading or Writing data to/from file
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{ char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open(“sample.dat"); // Associating the outfile to disk file sample.dat
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
17
Program - Reading or Writing data to/from file
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // Why do we want this ?
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close(); // No more your program can access the file sample.dat
// open a file in read mode.
ifstream infile;
infile.open(“sample.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data on the screen.
cout << data << endl;
18
Program - Reading or Writing data to/from file
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
// Alternatively we can use the following approach for reading data from file
while(!infile.eof())
{
infile >> data;
cout << data << endl;
}
19
Program - Writing data to a file
#include <iostream>
#include <fstream>
#include <iomanip.h>
using namespace std;
int main()
{ fstream outFile("table.txt", ios::out);
int nums[3][3] = { 897, 5, 837, 34, 7, 21623, 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();
}
20
Contents of a file table.txt
8 9 7 5 8 3 7 \n
3 4 7 1 6 2 3 \n
3 9 0 3 4 5 6 1 2 \n
<EOF>
21
Program demonstrates read and write functions
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ 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();
return 0;
22
}
File Pointers
• Each file object has two integer values associated with it :
– get pointer
– put pointer
• These values specify the byte number in the file where reading or
writing will take place.
• By default reading pointer is set at the beginning.
• By default writing pointer is set at the end (when you open file in
ios::app mode)
• There are times when you must take control of the file pointers
yourself so that you can read from and write to an arbitrary
location in the file.
23
File Pointers
• Both istream and ostream provide member functions for repositioning
the file-position pointer. These member functions are seekg ("seek get")
for istream and seekp ("seek put") for ostream.
• fl.seekg(offset, refposition);
• fl.seekp(offset, refposition);
• The argument to seekg and seekp normally is a long integer (offset), it
specifies the location in the file as a number of bytes from the file's
starting location.
• A second argument (reposition) can be specified to indicate the seek
direction, the seek direction can be
1. ios::beg (the default) for positioning relative to the beginning of a stream
2. ios::cur for positioning relative to the current position in a stream
3. ios::end for positioning relative to the end of a stream.
24
File Pointers
• Some examples of positioning the "get" file-position pointer are:
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
Note – tellg and tellp are used to get the position of istream and
ostream.
25
program demonstrates the seekg function
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file("letters.txt", ios::in); //open file letters.txt in read mode
char ch;
// sets the read position to the 5th byte from the beginning
file.seekg(5L, ios::beg);
// read the character
file.get(ch);
cout << "Byte 5 from beginning: " << ch << endl;
// sets the read position to the 10th byte from the end of file
file.seekg(-10L, ios::end);
file.get(ch);
cout << "Byte 10 from end: " << ch << endl;
26
program demonstrates the seekg function
// sets the read position to the 8th byte from the current position
file.seekg(8L, ios::cur); file.get(ch);
cout << "Byte 8 from current: " << ch << endl;
file.close();
return 0;
}
27
program demonstrates the tellg function
#include <iostream>
#include <fstream>
#include <ctype.h> // For toupper
int main(int)
{ 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; 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();
return 0;
28
}
string myText;
Program 1: // Read from the text file
# include <iostream> ifstream MyReadFile("filename.txt");
#include <fstream> // Use a while loop together with the getline
using namespace std; function to read the file line by line
{ {
// Create and open a text file // Output the text from the file
MyFile.close();
Output: NIT Warangal BTech CSE First Year
29
Program 2:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream FileName;
FileName.open("FileName.txt", ios::in);
if (!FileName) {
cout<<"File doesn’t exist.";
}
else {
char x; Output : NITWarangalBTechCSEFirstYear
while (1) {
FileName>>x;
if(FileName.eof())
break;
cout<<x;
}
}
FileName.close();
return 0;
}
30
Program 3:
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
Output:
fstream inFile;
NIT
inFile.open("FileName.txt", ios::in);
Warangal
string words;
BTech
while(inFile >> words)
CSE
{
First
cout << words << endl;
Year
}
inFile.close();
return 0;
}
31
Program 4:
#include <iostream> // Execute a loop If file successfully opened
int main()
{ // Press -1 to exit
fout.open("sample.txt"); }
32
// Close the File
fout.close();
// Creation of ifstream class object to read Output:
the file
ifstream fin;
NIT
// by default open mode = ios::in mode
Warangal
fin.open("sample.txt");
BTech
// Execute a loop until EOF (End of File)
CSE
while (getline(fin, line)) {
-1
// Print line (read from file) in Console
NIT
cout << line << endl;
Warangal
}
BTech
// Close the file
CSE
fin.close();
return 0;
}
33
int main()
Program 5: {
NIT
fout << line << endl; Warangal
BTech
// Increment the counter
CSE
i += 1; Ist