Working with Files
Here we will discuss working with files using Visual C++. You can send your programs output to a file, save it, call the file back, make changes, delete it --all that good stuff. If you choose to work with a file in your C++ program, you will need to include <fstream> . In you code, you will work with the file just as you would with a physical file: Open it, write the data, and close. Pretty simple.
Next, you will need to define the file you will be working with in the program. You can accomplish this with the syntax: ofstream NameOfFile; . It is good pratice to go ahead and declare that along with your variables. Afterwards, you can now open the file.
If your file is in the directory in which you are working, you will not need to include the path, if the file is say in your A:, then you must also include the path to the file, see below:
*Note: An additional option to the open function in ofstream can be declared after you specify the file name. This will tell the computer how the file will be opened, for output, or append. Output means a new file will be created. If another file with the same name exists, all data within that file will be erased... so be careful! To declare a file to be opened for output, you can include this after the file name, ios::out. BUT this is default, so when you say: YourFile.open("File_I_Made.dat"); will do the same as: YourFile.open("File_I_Made.dat" ios::out); .
To declare the file for append means to add to an existing file, with existing data. You will simply add: ios::app after the file name in the open function. If the file isnt' there, it will create one. And the data is added to the end of existing data.
Here is a code sample for opening a file for output, and append:
After you open the file, how are you sure that it did open it? If it did not, then obviously your program is not functioning properly. If the destination is full or the disk is write protected, yourFile.open(); can fail. So, to determine that it did open, is_open comes to the rescue! Syntax is: yourFile.is_open() - The is_open function will return a boolean value (true or false). If it is open, true - If not, false. Below is an example to test if you file opened:
There are various ways of testing, but generally you will use it in a condition. Almost any programmer you will talk to will tell you that 90% of a programs code is error handling. What to do if something didnt happen, or input not expected. You might get use to that, it will only make your programs better.
No Comments for this page.