C++ File Pointer And File Manipulators

What is a file pointer?

 A pointer is used to handle and keep track of the files being accessed. Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in output mode file), which tells the current position where reading or writing will take place with the use of opening modes and their respective manipulators.

Advertisements

These pointers help attain random access to the file. Like Moving at once to any area withinside the record rather than shifting through it sequentially.

Functions of file handling:

seekg():-

It is used to move the get pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekg (number of bytes ,Reference point); 	
Example: fin.seekg(10,ios::beg); 

tellg():-

tellg() is used to realize which they get pointer is in a file.

Syntax: file_pointer.tellg(); 
Example: int posn = fin.tellg(); 

seekp():-

seekp() is used to move the put pointer to the desired location concerning a reference point.

Syntax: file_pointer.seekp(number of bytes ,Reference point); 
Example: fout.seekp(10,ios::beg); 

tellp():-

tellp()is used to realize which they get pointer is in a file.

Syntax:     file_pointer.tellp(); 
Example:    int posn=fout.tellp(); 

What are the reference points available?

The reference points are:

ios::beg – These are used from the beginning of the file

ios::end – These are used from the end of the file

ios::cur – These are used from the current position in the file.

Files Usage

  • Data Preservation: Storing files in documents allows to hold records even though this system terminates.
  • Easy Data Access: Accessing records will become easy whilst there may be a large number of records and it’s far saved with inside the record, then these files may be accessed the use of the C++ commands.
  • Portability: It will become less difficult to switch records from one pc to any other with no changes.

Operations On Files

 Various operations that can be performed on a file are:  

  • Creation of a new file (fopen with attributes as “a”)
  • Opening an existing file (fopen).
  • Reading from file (fscanf or fgets).
  • Writing to a file (fprintf or fputs).
  • Moving to a specific location in a file (fseek, rewind).
  • Closing a file (fclose).

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

Example #1

1 #include<iostrea
2 #include<fstream>

fstream library

Before diving into each sub-topics, let us first learn about the header file we will be using to gain access to the file handling method. In C++, the fstream library is used to handle files, and it is dealt with with the help of three classes known ofstream, ifstream, and fstream.

ofstream:

This class helps create and write the data to the file obtained from the program’s output.

ifstream:

We use this class to read data from files and also known as the input stream.

fstream:

This class is the combination of both ofstream and ifstream. It provides the ability of creating, writing, and reading a file.

To access the following classes, you must include the fstream as a header file like how we declare iostream in the header.

After including the header file, there comes a question saying do we need to create the file within the program or else do we need to use an existing file. But this isn’t that difficult to answer because, in C++, we get four different methods to handle files

Opening Modes

What are opening modes?

An opening mode is a setting to control how the stream opens the file. An opening mode can be provided as a second parameter to the constructor of a file stream or its open() member function.

In the “std::ios” namespace we get all modes.

  • “r”- This mode specifies it is open for reading.

If the file does not exist, fopen() returns NULL.

  • “rb”– This mode specifies it is open for reading in binary mode.

 If the file does not exist, fopen() returns NULL.

  • “w”– This mode specifies it is Open for writing. If the file exists, its contents are overwritten.

If the file does not exist, it will be created.

  • “wb”- This mode specifies it is Open for writing in binary mode.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a” – This mode specifies it is Open for append. Data is added to the end of the file.

If the file does not exist, it will be created.

  • “ab” – This mode specifies it is Open for append in binary mode. Data is delivered to the end of the file.

If the file does not exist, it will be created.

  • “r+” – This mode specifies it is Open for both reading and writing.

 If the file does not exist, fopen() returns NULL.

  • “rb+” – This mode specifies it is Open for both reading and writing in binary mode.

If the file does not exist, fopen() returns NULL.

  • “w+”–  This mode specifies it is Open for both reading and writing.

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

Advertisements
  • “wb+”- This mode specifies it is open for both reading and writing in binary mode.       

If the file exists, its contents are overwritten. If the file does not exist, it will be created.

  • “a+” – This mode specifies it is open for both reading and appending.

If the file does not exist, it will be created.

  • “ab+” – This mode specifies it is Open for both reading and appending in binary mode.

    If the file does not exist, it will be created.

Example #2: For writing files

#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::out);
	if (!my_exfile) {
		cout << "File not created here!";
	}
	else {
		cout << "File got created!";
		my_exfile << "Example01";
		my_exfile.close();
	}
	return 0;
}

Output:

The file got created!

Closing File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Example #3: Reading from a File


#include <iostream>
#include <fstream>
using namespace std;
int main() {
	fstream my_exfile;
	my_exfile.open("my_exfile.txt", ios::in);
	if (!my_exfile) {
		cout << "No such file is present";
	}
	else {
		char ch;

		while (1) {
			my_exfile >> ch;
			if (my_exfile.eof())
				break;

			cout << ch;
		}

	}
	my_exfile.close();
	return 0;
}

Output:

Example01
Here, we got the output value which is stored in “example (a)”

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in the case of binary files.

Writing to a binary file?

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

address of data to be written on the disk

size of data to be written on the disk

number of such types of data

pointer to the file where you want to write.

Syntax:

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example #4 – Writing a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>
struct threeDig
{
   int d1, d2, d3;
};
int main()
{
   int n;
   struct threeDig dig;
   FILE *fptr;
   if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
       printf("Error! opening file");

       // Program exits if the file pointer returns NULL.
       exit(1);
   }

   for(n = 1; n < 5; ++n)
   {
      num.n1 = n;
      num.n2 = 5*n;
      num.n3 = 5*n + 1;
      fwrite(&num, sizeof(struct threeDig), 1, fptr); 
   }
   fclose(fptr); 
  
   return 0;
}

In this program, we create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers – n1, n2, and n3, and define it in the main function as num.

Now, inside the for loop, we store the value into the file using fwrite().

The first parameter takes the address of num and the second parameter takes the size of the structure threeNum.

Since we’re only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points to the file we’re storing the data.

Finally, we close the file.

Manipulators

What are Manipulators?

Manipulators are helping functions that can modify the input/output stream. It does not mean that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.

Types of Manipulators

There are various types of manipulators:

Manipulators without arguments: The most important manipulators defined by the IOStream library are provided below.

endl: It is defined in ostream. It is used to enter a new line and after entering a new line it flushes (i.e. it forces all the output written on the screen or in the file) the output stream.

ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.

ends: It is also defined in ostream and it inserts a null character into the output stream. It typically works with std::ostrstream, when the associated output buffer needs to be null-terminated to be processed as a C string.

flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the output written on the screen or in the file. Without flush, the output would be the same, but may not appear in real-time.

Example #5

#include <iostream>
#include <istream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    istringstream str("           Challenging");
    string line;
    // Ignore all the whitespace in string
    // str before the first word.
    getline(str >> std::ws, line);
  
    // you can also write str>>ws
    // After printing the output it will automatically
    // write a new line in the output stream.
    cout << line << endl;
    // without flush, the output will be the same.
    cout << "only an example" << flush;
    // Use of ends Manipulator
    cout << "\nc";
    // NULL character will be added in the Output

    cout << "a" << ends;
    cout << "t" << endl;
  
    return 0;
}

Output:

Challenging
only an example
cat

The header file iomanip provides a set of functions called manipulators which can be used to manipulate the output formats.

 They provide the same features as the ios(Input-output system) member functions and flags. Some manipulators are more convenient to use than their counterparts in the class(Input-output system) ios. such that, two or more manipulators can be used as a chain in one statement as shown below:

cout << manip1 << manip2 << manip3 << item;
cout << manip1 << item1 << manip2 << item2;

File Pointer & their Manipulation

The read operation from a file involves getting a pointer. It points to a specific location in the file and the reading starts from that location.

Then, the get pointer keeps moving forward which lets us read the entire file. Similarly, we can start writing to a location where the put pointer is currently pointing. The get and put are known as file position pointers and these pointers can be manipulated or repositioned to allow random access to the file

Summary

The C++ file handling is an effiecient tool to manage program output and data in files. In more advanced way to handing data is connecting C++ to a database system such as SQL server and manage data in an efficient way.

This articles talk about flat files manipulations, but you may like to try this examples with Microsoft excel program also.



Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version