Read from File
2002-01-31 16:57:04
Category: cpp:files
Description: Shows how to read text in from a file in c++
Author: detour
Viewed: 6056
Rating: (43 votes)


/* fileread.cpp by detour@metalshell.com
 *
 * Example of reading a text file.
 * 
 * http://www.metalshell.com/
 */
 
#include <iostream>
#include <fstream.h>
 
int main() {
    char inLine[128];
    char fname[24];
    ifstream inFile;
 
    cout << "Enter a file that contains text: ";
    cin >> fname;
 
    /* open the file */
    inFile.open(fname, ios::in);
 
    /* if opening didn't fail */
    if(!inFile.fail()) {
 
        while(!inFile.eof()) {
            inFile >> inLine;
            cout << inLine << endl;
        }
        
        inFile.close();
    } else 
        cout << "Error Opening File.";
 
    return 0;
}