|
File I/O
|
|
File input and output is extremely simple in C++ compared to C. It works just like reading and writting to standard I/O. In order to use the C++ functions needed to accomplish file I/O you must include the header file . Here is an example:
|
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream outputFile("file.txt"); //ofstream will create the file if it doesn't exist, ifstream will not
ifstream inputFile;
char myString[50];
cout << "Enter a string: ";
cin.getline( myString, 50, '\n');
cout << "Writting string to file...\n";
outputFile << myString;
outputFile.close();
inputFile.open("file.txt");
cout << "Reading string from file...\n";
inputFile.getline(myString, 50, '\n');
cout << myString;
system("pause");
return 0;
}
|
|
Here are two new data types, ofstream and ifstream. When a program open a file it asigns it a number called a handle in order to keep track of it, this is what is assigned to the ofstream and ifstream type variables every time you open a file. As you see there are two was of opening a file, at the declaration, "ofstream outputFile("file.txt");", and anywhere else by using open(), "inputFile.open("test.txt");".
Output works just like cout, and input works exactly like cin! Notice how I used getline() with inputFile and it worked exactly like it would with cin.
If a file is opened from an ifstream and the file does not exist, it will not create the file. Ofstream will create a non-existant file, but will also wipe out its contents. What if you wanted ifstream to create the file, and ofstream not to? Or have ofstream add to a file rather than delete it? Heres how:
|
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream outputFile("file.txt", ios::app); //ofstream will append to file
ifstream inputFile;
char myString[50];
cout << "Enter a string: ";
cin.getline( myString, 50, '\n');
cout << "Writting string to file...\n";
outputFile << myString;
outputFile.close();
inputFile.open("file.txt");
cout << "Reading string from file...\n";
inputFile.getline(myString, 50, '\n');
cout << myString;
system("pause");
return 0;
}
|
|
Here we have the same program from before, except we are now adding on to file.txt. Here are other options for files:
|
ios::app - Apend
ios::trunc - wipe out file
ios::ate - Set position at end of file
|
|
|