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

PPT10

chemistry

Uploaded by

DHRUV PALIWAL
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)
17 views

PPT10

chemistry

Uploaded by

DHRUV PALIWAL
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/ 52

C++ files and

streams
Introduction
• So far, we have been using the iostream
standard library, which provides cin and cout
methods for reading from standard input and
writing to standard output respectively.

• To perform file processing in C++, headerfiles


<iostream> and <fstream> must be included in
your C++sourcefile.
Streams
• The stream that supplies data to the program is known as input stream
and the one that receives data from the program is known as output
stream.
• the input stream extracts (or reads) data from the file and the output
stream inserts (or writes) data to the file
Streams
Files
• A file is a collection on information, usually stored
on a computer’s disk. Information can be saved to
files and then later reused.
• All files are assigned a name that is used for
identification purposes by the operating system
and the user. File Name and Extension

MYPROG.BAS
File Contents
BASIC program
MENU.BAT DOS Batch File
INSTALL.DOC Documentation File
CRUNCH.EXE Executable File
BOB.HTML HTML (Hypertext Markup Language) File
3DMODEL.JAVA Java program or applet
INVENT.OBJ Object File
PROG1.PRJ Borland C++ Project File
ANSI.SYS System Device Driver
README.TXT Text File 3
Process of Using a File
• Using a file in a program is a simple three-step
process
– The file must be opened. If the file does notyet
exits, opening it means creatingit.
– 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.
4
Contd…

5
File
stream
1. ios - all I/O operations classes
2. istream is for input e.g. as getline()
3. ostream is for output e.g. write()
4. ifstream – Input from file
5. ofstream – write to a file
6. fstream – I/O with a file
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
• Before data can be written toor read from a file,
the file must beopened.
ifstream inputFile;
inputFile.open(“customer.dat”);
6
Example
This program demonstrates the declaration of an fstream
object and the opening of a file.

1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main()
5. {
6. fstream dataFile; // Declare file stream object
7. char fileName[81];
8. cout << "Enter the name of a file you wish to open\n";
9. cout << "or create: ";
10. cin.getline(fileName, 81);
11. dataFile.open(fileName, ios::out);
12. cout << "The file " << fileName << " was opened.\n";
13. return 0; Output:
14. }
Enter the name of a file you wish to open
or create: mystuff.dat
The file mystuff.dat was opened. 7
Opening a File at Declaration
fstream dataFile(“names.dat”, ios::in | ios::out);
This program demonstrates the opening of a file at the
time the file stream object is declared.

1.#include <iostream>
2.#include <fstream>
3.using namespace std;
4.int main()
5. {
6.fstream dataFile("names.dat", ios::in | ios::out);
7.cout << "The file names.dat was opened.\n";
8.return 0; 9. }
Output:
The file names.dat was opened.
8
Testing for Open Errors

dataFile.open(“cust.dat”, ios::in);
if (!dataFile)
{ cout << “Error opening file.\n”; }

dataFile.open(“cust.dat”, ios::in);
if (dataFile.fail())
{ cout << “Error opening file.\n”; }

9
Closing a File
A file should be closed when a program is finished using it.
This program demonstrates the close function.

1.#include <iostream> Output:


2.#include <fstream> File was created successfully.
3.using namespace std; Now closing the file.
4.int main()
5.{ fstream dataFile;
6. dataFile.open("testfile.txt", ios::out);
7.if (!dataFile) 8.
{ cout << "File open error!" << endl; return 0;
}
9. cout << "File was created successfully.\n";
10. cout << "Now closing the file.\n";
11. dataFile.close();
10
12. return 0; }
File Default Open Modes
File Type Default Open Mode
ofstream 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).

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

11
File Mode Flags
File Mode Flag Meaning

ios::app Append mode. Ifthe 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 notexist.
ios::ate If the file already exists, the program goes directly to the end of it. Output
may be written anywhere in the file.
ios::binary 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.)

ios::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.
ios::nocreate If the file does not already exist, this flag will cause the open function to fail.
(The file will not becreated.)
ios::noreplace If the file already exists, this flag will cause the open function to fail. (The
existing file will not beopened.)
ios::out Output mode. Information will be written to the file. By default, the file’s
contents will be deleted if it already exists.
ios::trunc If the file already exists, its contents will be deleted (truncated). This is the
default mode used by ios::out.
12
Write on file
• The stream insertion operator (<<) may be used to
write information to afile.
outputFile << “I love C++ programming !”
Example
This program uses the << operator to write information to a file.

1.#include <iostream>
2.#include <fstream> Output:
3.using namespace std; File opened successfully.
4.int main() Now writing information to the file.
5.{ fstream dataFile; Done.
6. char line[81];
7. dataFile.open("demofile.txt", ios::out);
8. if (!dataFile)
9. { cout << "File open error!" << endl; return 0; }
10. cout << "File opened successfully.\n";
11. cout << "Now writing information to the file.\n";
12. dataFile << "Jones\n";
13. dataFile << "Smith\n";
14. dataFile.close();
14
15. cout << "Done.\n"; return 0; }
Example
This program writes information to a file, closes the file, then reopens it
and appends more information.
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main()
5. { fstream dataFile;
6. dataFile.open("demofile.txt", ios::out);
7. dataFile << "Jones\n";
8. dataFile << "Smith\n";
9. dataFile.close();
10. dataFile.open("demofile.txt", ios::app);
11. dataFile << "Willis\n";
12. dataFile << "Davis\n";
13. dataFile.close();
14. return 0; } 15
Read from file
• The stream extraction operator (>>) may be used
to read information from afile.

16
Example
This program uses the >> operator to read information from a file.
Output:
1. #include <iostream> File opened successfully.
2. #include <fstream> Now reading information from the file.
3. using namespace std; Jones
Smith
4. int main() Willis
5. { fstream dataFile; Davis
6. char name[81]; Done.
7. dataFile.open("demofile.txt", ios::in);
8. if (!dataFile)
9. { cout << "File open error!" << endl; return 0; }
10.cout << "File opened successfully.\n";
11.cout << "Now reading information from the file.\n";
12.for (int count = 0; count < 4; count++) 13.
14. dataFile.close();
{ dataFile >> name; cout << name << endl; }
15. cout << "Done.\n";
16. return 0; }
17
Detecting the End of aFile
• The eof() member function reports when the
end of a file has been encountered.

if (inFile.eof())
inFile.close();

• 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.
18
Example
This program uses the file stream object's eof() member function to detect
the end of the file.
1.#include <iostream> File opened successfully.
2.#include <fstream> Reading information from the file.
3.using namespace std; Jones
4.int main() Smith
5.{ fstream dataFile; Willis
6. char name[81]; Davis
7. dataFile.open("demofile.txt", ios::in); Done.
8.if (!dataFile) 9.
10. { cout << "File open error!" << endl; return 0; }
11. cout << "File opened successfully.\n";
12. cout << "Reading information from the file.\n";
13. dataFile >> name; / / Read first name from the file
14. while (!dataFile.eof())
15. { cout << name << endl;
16. dataFile >> name; }
17. dataFile.close();
18. cout <<"\nDone.\n";
return 0; } 19
Example
This program uses the file stream object's eof() member function to detect the
end of the file.
Output:
1. #include <iostream>
2. #include <fstream> Jones
3. using namespace std; Smith
4. int main() Willis
5. { fstream nameFile; Davis
6. char input[81];
nameFile.open("demofile.txt", ios::in);
7. if (!nameFile)
8. { cout << "File open error!" <<endl; return 0; }
9. nameFile >> input;
10. while (!nameFile.eof())
11. { cout << input <<endl; nameFile >> input; }
12. nameFile.close();
13. return 0; 21
14. }
Member Functions for Readingand
Writing Files
• File stream objects have member functions for
more specialized file reading andwriting.

20
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.)

22
Example
This program uses the file stream object's getline member function toread a line of
information from the file.
Output:
1. #include <iostream>
Jones
2. #include <fstream>
Smith
3. using namespace std;
Willis
4. int main()
5. { fstream nameFile; Davis
6. char input[81];
nameFile.open("demofile.txt", ios::in);
7. if (!nameFile)
8. { cout << "File open error!" << endl; return 0; }
9. nameFile.getline(input, 81); / / use \n as a delimiter
10. while (!nameFile.eof())
11. { cout << input <<endl;
12. nameFile.getline(input, 81); / / use \ n as a delimiter }
13. nameFile.close(); 23
14. return 0; }
The get Member Function
This program asks the user for a file name. The file is opened and its contents
are displayed on the screen.

1.#include <iostream>
2.#include <fstream>
3.using namespace std;
4.int main()
5.{ fstream file;
6. char ch, fileName[51];
7. cout << "Enter a file name: ";
8. cin >> fileName;
9. file.open(fileName, ios::in);
10. if (!file)
11. { cout << fileName << “ could notbe opened.\n"; return 0; }
12.file.get(ch); / / Get a character
13. while (!file.eof())
14. { cout <<ch; file.get(ch); / / Get another character }
15. file.close();
24
16. return 0; }
More get() Functions
In addition to the form shown earlier, get function is overloaded in several different
ways. The prototype for the three most commonly used overloaded forms are shown
here:

istream &get(char *buf, streamsize num);


istream &get(char *buf, streamsize num, char delim);
int get( );

The first form reads characters into the array pointed to by buf until either num-1
characters have been read, a newline is found, or the end of the file has been
encountered.

The second form reads characters into the array pointed to by buf until either num-1
characters have been read, the character specified by delim has been found, or the
end of the file has been encountered.

The third overloaded form of get( ) returns the next character from the stream. It
returns EOF if the end of the file is encountered.

24
The put Member Function
This program demonstrates the put memberfunction.

1. #include <iostream>
2. #include <fstream> using namespace std;
3. int main()
4. { fstream dataFile("sentence.txt", ios::out);
5. char ch;
cout << "Type a sentence and be sure to end it with a ";
cout <<"period.\n";
6. Output:
7. while (1) Type a sentence and be sure to end
8. { cin.get(ch); it with a period.
9. dataFile.put(ch); I am on my way.
10. if (ch =='.') Resulting Contents of the File
11. break; SENTENCE.TXT:
12. } I am on my way.
13. dataFile.close();
14. return 0; } 25
Example
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main()
5. {
6. ifstream in("test");
7. if(!in) {
8. cout << "Cannot open file.\n";
9. return 1;
10. }
11. in.ignore(10, ' ');
12. char c;
13. while(in) {
14. in.get(c);
15. if(in) cout << c;
16. }
17. in.close();
18. return 0;
19. }
File pointers to read/write from
binary files

• To write nbytes:
– write (const char* buffer, int n);
• To read n bytes (to a pre-allocated buffer):
– read (char* buffer, int num)
Example
1. #include<iostream>
2. #include <fstream>
3. using namespace std;
4. int main()
5. { int a[] ={10,23,3,7,9,11,25};
6. fstream fs;
7. fs.open("myfile.txt", ios::binary | ios::out);
8. fs.write((char*) &a, sizeof(a));
9. fs.close();
10. for(int i = 0; i < 7; i++) a[i] = 0;
11. fs.open("myfile.txt", ios::in | ios::binary);
12. fs.read((char*) &a, sizeof(a));
13. for(int i = 0; i < 7; i++) cout << a[i] << " ";
14. fs.close(); }
Random Access Files
• Random Access means non-sequentially accessing
information in afile.

29
Mode Flags

Mode Flag Description

ios::beg The offset is calculated from the beginning of the file.

ios::end The offset is calculated from the end of the file.

ios::cur The offset is calculated from the current position.

30
Contd…
Statement How it Affects the Read/WritePosition
File.seekp(32L, ios::beg); Sets the write position to the 33rd byte
(byte 32) from the beginning of the file.
file.seekp(-10L, ios::end); Sets the write position to the 11th byte
(byte 10) from the end of the file.
file.seekp(120L, ios::cur); Sets the write position to the 121st byte
(byte 120) from the currentposition.
file.seekg(2L, ios::beg); Sets the read position tothe 3rd byte
(byte 2) from the beginning of the file.
file.seekg(-100L, ios::end); Sets the read position to the101st byte
(byte 100) from the end of the file.
file.seekg(40L, ios::cur); Sets the read position to the41st byte
(byte 40) from the currentposition.
file.seekg(0L, ios::end); Sets the read position to the end of the
file. 31
File position 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.

• The seek direction can be


– ios::beg (the default) for positioning relative to the beginning of
a stream
– ios::cur for positioning relative to the current position in a
stream
– ios::end for positioning relative to the end of a stream.
Continued…
• 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 offileObject


fileObject.seekg( n, ios::end );

• position at end of fileObject


fileObject.seekg( 0, ios::end );
Example
This program demonstrates the seekgfunction.

1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main()
5. { fstream file("demofile.txt", ios::in);
6. char ch;
7. file.seekg(5L, ios::beg);
8. file.get(ch);
9. cout << "Byte 5 from beginning: " << ch <<endl;
10. file.seekg(-10L, ios::end);
11. file.get(ch);
12. cout << "Byte 10 from end: " << ch<< endl;
13. file.seekg(3L, ios::cur);
14. file.get(ch);
15. cout << "Byte 3 from current: " << ch<< endl;
16. file.close();
34
17. return 0;}
File pointers – bookmarks in the file
• Get Pointer tells the current location during file reading
• Put Pointer tells the current position during file writing
• A file pointer is not like a C++ pointer but works like a book-
mark in a book
• These pointers help attain random access in file for faster
access in comparison to a sequential access
File pointers – seek and tell

• Tell function - just examine the file location

• Seek function – actually set the bookmark in a file


G and P in – seekg(), tellg(), seekp(), tellp()

• G – (as Get) is for file read operation

• P – (as Put) is for file write operation


File pointers – seekg(), tellg(), seekp(), tellp()

• seekg() and tellg() functions allow you to set and examine


the get_pointer in the given file

• seekp() and tellp() functions perform these operations on


the put_pointer.
Current, beginning and & end
References for seek and tell functions

• ios::beg
• ios:cur
• ios:end
Command Line Arguments
▪ In C/C++ it is possible to accept arguments from the
command line.

▪ We will be passing arguments to the main function,


which we have always left empty.

▪ Command line arguments are passed as character


arrays, where each parameter is separated by space.

▪ Comes into the program as two arguments


argc – Number of parameters
argv – Parameter list
34
An example program
#include <iostream>
using namespace std;

int main(int argc, char *argv[])


{
for (int i=0; i<argc; i++)
cout << "This is Argument number #"
<< i
<< "->"
<< argv[i] << endl;
return 0;
}

34
Command Line Arguments
Conventional rules:

▪ First argument (argv[0]) will always be the name of the


calling program.
▪ argc will always be at least 1
▪ The first argument is always argv[0]
▪ The last argument is always argv[argc-1]
▪ argv[argc] will always be a null pointer

34
Command Line Arguments
Conventional rules:

▪ Arguments are always passed as character strings.


▪ Numbers must be converted from characters to integers,
floats, doubles, etc.
▪ The names argc and argv are traditional but arbitrary.
▪ You may name these two parameters to main( ) anything
you like.

34
Command Line Arguments
use:

▪ A program that wants its parameters to be set when it is


executed would use command line arguments.

▪ One common use is to write a function that takes the


name of a file and outputs the entire text of it onto the
screen (program on next slide).

34
Command Line Arguments
use:
#include <fstream>
#include <iostream>
using namespace std;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) // argc should be 2 for correct execution
cout<<"You have to run it like: "<< argv[0] <<" <filename>\n";
else {
ifstream the_file ( argv[1] ); // We assume argv[1] is a filename to open
if ( !the_file.is_open() ) // check to see if file opening succeeded
cout<<"Could not open file\n";
else {
char x;
while ( the_file.get ( x ) ) //the_file.get ( x ) returns false if the end of the file
cout<< x; // is reached or an error occurs.
}
}
}
34
Thank You

You might also like