Very Simple File Example Program
You can just cut this program and paste it into Visual Studio:
/***********
Jim Engel
A very simple file example where we:
read in lines of test,
write them to a file, close the file
open the file for input
display the lines of text.
****************/
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
int main()
{
char lineOfText[128];
char NameOfOurFile[64] = "ThisTestFile.txt";
cout << "First we read in some text lines and put em in a file...\n\n";
/***************** WRITE SAMPLE FILE ****************/
ofstream thisOFile; // create the file object.
thisOFile.open( NameOfOurFile ); // Open the file
if (thisOFile.fail () )
{ cout << "File open Fails !\n\n" ;
return 0;
}
while ( true ) {
cout << "Enter a line of text: ";
cin.getline(lineOfText, 100);
if ( lineOfText[0] == 0 || lineOfText[0] == ' ' )
break;
thisOFile << lineOfText << endl ; // put one line of text in file.
}
thisOFile.close();
cout << "Text Entry complete\n";
/***************** LOAD AND DISPLAY SAMPLE FILE ****************/
cout << "\nNow load and display file: " << NameOfOurFile << endl << endl ;
ifstream thisIFile; // Create the file object
thisIFile.open( NameOfOurFile ); // Open the actual file
if (thisIFile.fail () )
{ cout << "File open Fails!\n\n" ;
return 0;
}
cout << "These are our read in text lines:\n";
while ( true)
{ thisIFile.getline ( lineOfText, 100 ); // read in one line of text.
if ( !thisIFile ) { // check for end of file.
cout << endl<< "End of file found." << endl;
break;
}
cout << lineOfText << endl ;
}
thisIFile.close();
cout << endl << "File read and display complete\n";
return 0;
}