Professional Documents
Culture Documents
Chapter 8 Examples
Chapter 8 Examples
Chapter 8 Examples
#include <iostream>
#include <fstream> // step (a)
#include <stdlib.h> // used by exit( )
#include <conio.h>
void main ()
{
// mandatory when declaring a file for output
ofstream outFile; // step (b)
outFile.open ("f:\\file.txt"); // step (c)
// statements
int a=1, b=2, c=3;
outFile << a << " " << b << " " << c << endl; // step (e)
/* Output:
*/
// Program 8.2 Writing output to an external file
// Example to write a text file by declaring logical file as fstream.
// Note the change in file opening statement.
#include <iostream>
#include <fstream> // required for file processing functions
#include <stdlib.h>
#include <conio.h>
void main()
{
const char filename[] = "f:\\Out8_2.txt";
int i, value1, value2;
fstream result; // logical filename declaration
// associate logical and physical file, and open file for output
result.open(filename, ios::out);
----------------------------------------------------------
*/
// Program 8.3 Reading input from an external file
#include <iostream>
#include <fstream> // step (a)
#include <stdlib.h> // used by function exit( )
#include <conio.h>
void main ()
{
// mandatory when declaring a file for input
ifstream inFile; // step (b)
inFile.open ("f:\\file.txt"); // step (c)
int a, b, c;
inFile >> a >> b >> c; // step (e)
/*
If a file named file.txt is created in F: drive.
The file details are
4 5 6
----------------------------------------------------------
Execution Window:
Data read from input file is 4, 5 and 6
#include <iostream>
#include <fstream> // required by file processing functions
#include <stdlib.h>
#include <conio.h>
void main()
{
int num = 0, value;
fstream data_input; // declaration of input file variable
{
if (value > 10) num++;
// continue reading data from file and store to variable value
data_input >> value;
}