Menu
C++ Tutorials

C++

Reading Text Files



Tutorials > C++ > Reading Text Files

View Full Source

Introduction

In the previous tutorial, we learnt how to write ascii data to a text file. This tutorial will explain how to read data from a text file. Having knowledge of both these tutorials will allow you to read and write textual data as you please, providing great storage and retrieval mechanisms.

Contents of main.cpp :


The same headers that are required for writing a file are needed for reading a file.

#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <stdio.h>

using namespace std;

int main()
{

For C file input, we open the file in the same way as in the previous tutorial. The only change required is the mode to open the file in. The mode must be set to "r" which signifies that the file will be read from.

	// C File Input
	//--------------
	FILE *inFile = fopen("in.txt", "r");

fopen returns NULL if the file cannot be read from or if the file does not exist.

	if (!inFile)
	{
		printf("Cannot find in.txt\n");
		return 1;
	}

If you would like to read a single character from a file, the fgetc function can be used. The function takes the FILE pointer as the only parameter and returns the character read from the file. NULL is returned if the current file position reaches the end of the file. The code below prints out the first few characters until a newline is reached.

	char ch;
	while ((ch = fgetc(inFile)) != '\n')
		cout << ch;

	cout << endl;

Reading an entire string follows the same approach. The fgets function allows an entire string of characters to be read from the file. The first parameter specifies where the data read should be stored. The second parameter indicates the maximum amount of characters to read and the last parameter takes the FILE pointer to the file being read from. Characters will be read up to either the maximum value specified or up to a newline if found before.

	char line[100];
	fgets(line, 100, inFile);
	cout << line;

A function similar to scanf is available for files. This function is not surprisingly the fscanf function. The first parameter takes the FILE pointer and the second parameter is used to specify the format string. The rest of the parameters are determined by your format string. The code below reads 3 integers from the text file.

	int a, b, c;
	fscanf(inFile, "%d %d %d", &a, &b, &c);

	cout << a << " " << b << " " << c << endl;

Once again we make sure that the file is closed.

	fclose(inFile);

	cout << endl;

C++ file input is very similar to output. An ifstream (input stream) object is created. We pass the filename when creating the object to automatically open it upon creation of the object.

	// C++ File Input
	//----------------
	ifstream fin("in.txt");

The next step is to check whether the file can be read from and if the file exists.

	if (!fin.good())
	{
		cout << "Cannot find in.txt" << endl;
		return 1;
	}

The ifstream object has a get method which simply returns the next character from the file. This has the same effect as the fgetc function.

	while ((ch = fin.get()) != '\n')
		cout << ch;

	cout << endl;

The equivalent to the fgets function is the getline method. This method takes the character storage location as the first parameter and the maximum number of characters to read as the second parameter.

	fin.getline(line, 100);
	cout << line << endl;

The ifstream object can be used in the same way as the cin object. You can simply use the redirection operators to extract data from the text file. The code below reads 3 integers from the file.

A new keyword, ws is shown below. If you redirect the input to this ws keyword, it basically causes all white space to be eaten. This will make sure that any newlines, carriage returns or extra spaces are read and disposed of, allowing the next line to be read as per normal. You may find that without using ws, that the next time you read a word, a newline or space is returned.

	a = b = c = 0;
	fin >> a >> b >> c >> ws;
	cout << a << " " << b << " " << c << endl;

One function that I have found extremely useful is the getline function. The first parameter indicates what stream you are reading from and the second parameter specifies a string variable that will store the data read from the stream.

This function has 2 advantages :

  • Strings can be used instead of character strings.
  • The maximum number of characters to be read is not needed. The entire line is read, no matter what the length.
	string str;
	getline(fin, str);
	cout << str << endl;

Once again we close off the file as required.

	fin.close();

	system("pause");

	return 0;
}

Well done. You should now have the ability to read and write text files, allowing you to store data generated from your programs for later use. Almost all useful programs allow you to load and save data of some sort.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 37 - Writing Text Files Tutorial 39 - String Streams >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links