Object
Write a program that reads a string from a file and prints it on the screen.
(download example9.txt)
Algorithm
- Create an ifstream object inFile to handle input operations on a file.
- Declare a string variable line.
- Open the file named example9.txt using inFile.open().
- IF the file fails to open,
- Write “Error: Unable to open the file”.
- Exit.
- [End of IF structure.]
- WHILE getline() returns False
- Write each line onto the screen.
- [End of WHILE loop.]
- Close the file.
- Exit.
Flowchart

C++ Source Code
// program 112
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile("example9.txt");
if (!inFile.is_open())
{
cout << "Error: Unable to open the file" << endl;
return 1;
}
string line;
while (getline(inFile, line))
{
cout << line << endl;
}
inFile.close();
return 0;
}
C Source Code
/*program 112*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char string[800];
if((fptr = fopen("example9.txt","r"))==NULL)
{
puts("Error: Unable to open the file");
exit(1);
}
while(fgets(string, 799, fptr) != NULL)
printf(string);
fclose(fptr);
return 0;
}
Output
What is stream in C++?
Stream refers to a stream of characters to be transferred between program thread and i/o.
