Reading from a text file in C and C++
Source listing
//=============================================================
// File: IODemo.cpp
// Purpose: Program demonstrates how to open and read lines from
// simple text files in both C and CPP. See comments in
// the source files for details.
// Author: Dr. Rick Coleman
//=============================================================
// Headers required for file I/O in C
#include <stdio.h>
// Headers required for file I/O in C++
#include <iostream>
#include <fstream>
// Headers required for both C and C++
#include <string>
using namespace std;
#define datafile "IODemo.dat"
// Function Prototypes
void GetNextLine_C(FILE *fp, char *line, int lineLen);
void GetNextLine_CPP(ifstream& inFile, char *line, int lineLen);
int main(int argc, char **argv)
{
// Vars used in the C I/O demo
FILE *fp; // Pointer to file
// Vars used in the C++ I/O demo
ifstream inFile; // Input file stream
// Vars used in both demonstrations
char str[128]; // Character array to hold lines read from the file
//---------------------------------------------
// Demonstrate file I/O in Standard C
//---------------------------------------------
printf("Demonstrating file I/O in Standard C\n");
printf("Opening file...\n");
// Open the file for reading, checking to make sure it was successfully opened
if((fp = fopen(datafile, "r")) == NULL)
{
// fopen() returns NULL if the file could not be found or
// if for some other reason the open failed.
printf("Unable to open file %s\nProgram terminating...\n");
return 0;
}
// File was successfully opened so call the C function to read
// all lines from the file.
printf("Printing lines in file...\n\n");
while(true)
{
GetNextLine_C(fp, str, 128);
if(strlen(str) == 0) // End of File reached
break; // terminate the loop
else
{
printf("%s\n", str); // Print the line
}
} // end eternal while() loop
fclose(fp); // Close the data file
printf("\n\ndone...\n\n");
//-----------------------------------------------------------------------
// Now we do the same thing in C++
//-----------------------------------------------------------------------
cout << "Demonstrating file I/O in C++\n";
cout << "Opening file...\n";
// Open the file for reading, checking to make sure it was successfully opened
inFile.open(datafile, ifstream::in);
if(!inFile.is_open())
{
// inFile.is_open() returns false if the file could not be found or
// if for some other reason the open failed.
cout << "Unable to open file %s\nProgram terminating...\n";
return 0;
}
// File was successfully opened so call the C++ function to read
// all lines from the file.
cout << "Printing lines in file...\n\n";
while(true)
{
GetNextLine_CPP(inFile, str, strlen(str));
if(inFile.good())
cout << str << "\n"; // Print the line
else
break; // terminate the loop
} // end eternal while() loop
fclose(fp); // Close the data file
cout << "\n\ndone...\n\n";
return 0;
}
/**************************************************************/
/* GetNextLine_C */
/* */
/* Purpose: Read a line from a data file. Returns void string */
/* if end of file is reached. */
/* Language: C */
/* Args: fp -- pointer to open file. */
/* line -- Character array to place the line in. */
/* lineLen -- Length of the character array line. */
/* Returns: void */
/**************************************************************/
void GetNextLine_C(FILE *fp, char *line, int lineLen)
{
int done = false;
while(!done)
{
if((fgets(line, lineLen, fp)) == NULL) // Read a line from the file
{
strcpy(line, ""); // Return an empty string to flag EOF
return;
}
// Remove the newline character from the end of the line
// Explanation: the function fgets() used to read lines from the
// file reads all characters up to and including the newline character
// at the end of a line in the file. This character is removed by
// overwriting it with a null terminator. For example: if the first
// line in the text file was "testing" it would be read into the
// character array as | t | e | s | t | i | n | g | \n | \0 |...
// The previous command overwrites the newline (\n) giving
// | t | e | s | t | i | n | g | \0 | \0 |...
if(strlen(line) > 0)
line[strlen(line)-1] = '\0';
if(strlen(line) == 0) // Skip any blank lines
continue;
else if(line[0] == '#') // Skip any comment lines
continue;
else done = true; // Got a valid data line so return with this line
}
}
/**************************************************************/
/* GetNextLine_CPP() */
/* */
/* Purpose: Read a line from a data file. */
/* Language: C */
/* Args: inFile -- istream pointer */
/* line -- Character array to place the line in. */
/* lineLen -- Length of the character array line. */
/* Returns: void */
/**************************************************************/
void GetNextLine_CPP(ifstream& inFile, char *line, int lineLen)
{
int done = false;
while(!done)
{
inFile.getline(line, 128);
if(inFile.good()) // If a line was successfully read
{
if(strlen(line) == 0) // Skip any blank lines
continue;
else if(line[0] == '#') // Skip any comment lines
continue;
else done = true; // Got a valid data line so return with this line
}
else
{
strcpy(line, "");
return;
}
} // end while
}