Using the open(), eof() and getline() member functions to open and read a file content line by line C++ code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the open(), eof() and getline() member functions to open and read a file content line by line in C++ programming

To show: How to use the open(), eof() and getline() member functions to open and read a file content line by line in C++ programming

 

Create a text file on drive C, name it readfile.txt, paste the following text and save it.

 

This is readfile.txt file content. Just sample text, opening

for reading by using getline() member function.

There are four lines of text to be read from.

This is just a plain simple reading text from a file.

 

Then run the following program.

 

// using open(), eof() and getline() member functions

#include <iostream>

#include <fstream>

using namespace std;

 

void main(void)

{

char filename[70];

ifstream inputfile;

char FirstLine[70];

char SecondLine[70];

char ThirdLine[70];

 

// prompt user for file name to be opened

cout<<"Enter the filename to be opened: ";

 

// read and store the file name

cin>>filename;

 

// test open file for reading

inputfile.open(filename);

 

// if not the end of file

if(!inputfile.eof())

{

cout<<"\nThe first line of text is: \n";

inputfile.getline(FirstLine, 70);

cout<<FirstLine<<'\n';

cout<<"The second line of text is: \n";

inputfile.getline(SecondLine, 70);

cout<<SecondLine<<endl;

cout<<"The third line of text is: \n";

inputfile.getline(ThirdLine, 70);

cout<<ThirdLine<<endl;

// we leave the other line of text

}

}

 

Output example:

 

Enter the filename to be opened: C:\readfile.txt

The first line of text is:

This is readfile.txt file content. Just sample text, opening

The second line of text is:

for reading by using getline() member function.

The third line of text is:

There are four lines of text to be read from.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index