0% found this document useful (0 votes)
13 views

Files-Functions and Operations (2)

Uploaded by

depanimokshith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Files-Functions and Operations (2)

Uploaded by

depanimokshith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Lecture 05:

Files – Functions and Operations

Dr. Manjubala Bisi


Assistant Professor,
Department of CSE,
NIT Warangal.
1
Files (Streams)
• All programs we’ve seen so far are –

1. Reading data from standard input device (keyboard)

2. Writing data to standard output device (screen).

• Output would be lost as soon as we exit from the program


(Ordinary variables (even records and arrays) are kept in
main memory which is temporary and rather limited in
size).

2
How do we store data permanently ?
• Store data in secondary storage devices (floppy disk,
hard disk, tape, etc.).

• Stream is an interface supplied by the I/O system of


C++ between the programmer and the actual device
being accessed (terminals, disks and tape drives).

• A stream (a general name given to flow of data) is a


sequence of bytes. It acts either as a source from
which the input data can be obtained or as a
destination to which the output data can be sent.
3
Files (Streams)

• Different streams are used to represent different kinds


of data flow.

• Each stream is associated with a particular class


(collection of data and functions associated with the
data), which contains member functions and
definitions for dealing with that particular kind of
data flow.

• All files are assigned a name that is used for


identification purposes by the operating system and
the user.
4
Files (Streams)
• We have used streams already !
– cin
• Input stream connected to keyboard (standard input device).
– cout
• Output stream connected to screen (standard output device).

• Can we define other streams to or from the files (instead


of standard input/output devices) ?
– Yes

• 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.

Input Stream Extraction from


input stream
Input device

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

istream class ostream class

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.

4. Use the file.

5. Close the file.

(C++ views file as a sequence of bytes, Ends with


end of file (EOF) marker)
10
Opening a File
• File must be opened before you can read from it or write to it.
• Either the ofstream or fstream may be used to open a file for
writing and ifstream object is used to open a file for reading
purpose only.

• 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

Mode Flag Description

ios::app Append mode. All the output to that file to be appended to


the end.

ios::ate Open a file for output and move the read/write control to the
end of the file.

ios::in Open a file for reading.

ios::out Open a file for writing.

ios::trunc If the file already exists, its contents will be truncated before
opening the file.

ios::binary Binary 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

– ofstream outfile; // Declaration


– outfile.open("file.dat", ios::out | ios::trunc ); //file.dat is a disk file

• 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.

• Following is the standard syntax for close() function, which is a


member of fstream, ifstream, and ofstream objects.

– 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

char get(); put();

One word >> (extraction operator) << (insertion operator)

>=1 word getline(); << (insertion operator)

objects read() write()

Binary data Same as above Same as above

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

int main() while (getline (MyReadFile, myText))

{ {

// Create and open a text file // Output the text from the file

ofstream MyFile("filename.txt"); cout << myText;


}

// Write to the file // Close the file


MyReadFile.close();
MyFile << "NIT Warangal BTech CSE First Year";
return 0;

// Close 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

#include <fstream> while (fout) {

using namespace std;


// Read a Line from standard input

// Driver Code getline(cin, line);

int main()
{ // Press -1 to exit

// Creation of ofstream class object if (line == "-1")

ofstream fout; break;

string line; // Write line in file


fout << line << endl;

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: {

#include <fstream> // Create an output file stream object

#include <iostream> ofstream fout;

#include <string> // Open a file named "NewFile.txt" for


writing
fout.open("NewFile.txt");
// Use the standard namespace
using namespace std;
// Check if the file opened successfully
if (!fout) {
// Print an error message if the file
couldn't be
// opened
cerr << "Error opening file!" << endl;
// Return 1 to indicate failure
return 1;
34
}
// Declare a string variable to hold each line of // Close the file after writing
text
fout.close();
string line;
// Initialize a counter to limit input to 5 lines
// Print a success message
int i = 0;
cout << "Text successfully written to
// Prompt the user to enter 5 lines of text NewFile.txt"
cout << "Enter 5 lines of text:" << endl; << endl;
// Loop to read 5 lines of input from the user
while (i < 5) { // Return 0 to indicate successful
// Read a line of text from standard input execution
Output:
getline(cin, line); return 0;

// Write the line of text to the file } Enter 5 lines of text:

NIT
fout << line << endl; Warangal

BTech
// Increment the counter
CSE
i += 1; Ist

Text successfully written to NewFile.txt


}
35
36

You might also like