- Part 1: Variables and Data Types
- Part 2: Arrays
- Part 3: Functions
- Part 4: Conditional Statements
- Part 5: Looping
- Part 6: Pointers
- Part 7: Objects
- Part 8: Complex Data Types
File Input and Output
Like with working with <iostream>, there is also a library for working with files, <fstream>.
Like with working with streams in <iostream>, the <fstream> library contains common functionality for working with files. These include the functions open(), get(), good(), and close().
To work with a file, it must be opened. The operating system connects the file to the software requesting access. In C++, the functions also needs an additional parameter, how to open the file.
File streams are like any other streams in C++: they work in one direction. Opening a file for input means it cannot be used for output until it is closed. The same is true for output. This means that the direction of input is very important.
The get() function does as it name suggests, it “gets” data from a stream or other source. The type of data returned from the function is influenced by what type of variable the result is placed. The function makes no assumptions and will place the data into whatever type of the variable used with it.
The work of the function good() does not seem as obvious based on its name. It tests if there is still data from the source. It tests if the stream is still “good” for use for input functionality.
As was mentioned with open(), a file is either “open” or “closed.” If a file is “open,” it is being used by some process for either input or output. Otherwise, it is “closed.”
In order to use the file or for some other software to use it, a file must be closed. The last operation of working with a file should always be to close it.