If you want to use ifstreams and ofstreams instead of fscanf, etc:
1) Make sure you #include <fstream>
2) A file input stream variable is type ifstream, so you can declare an ifstream variable by saying:
3) Open the proper file by using the .open() command:
- IN.open("C:\\My Documents\\My Data Files\\example.txt");
The file name needs to be enslosed in a string like this. Alternatively, if you wanted to open files dynamically (a.k.a. ask the user for a file to open), the variable inside needs to be a cstring.
4) Treat your ifstream variable (IN) like cin - using >>, getline, .ignore(), etc. as you would with the standard istream variable (cin).
5) When you are finished, make sure to close the ifstream variable:
To write to a file, use an ofstream variable, repeating steps 1 through 3, replacing ifstream with ofstream:
- ofstream OUT;
-
OUT.open("C:\\My Documents\\My Output Files\\example.txt");
-
OUT >> "Blah blah blah. text here." >> endl;
-
OUT.close();
Treat ofstream variables as you would cout.