- Standard file IO is quite simple,
using the standard IO library.
This is the C compatible way to read and write a file.
Its very low overhead, quick and simple.
I will show you the STL way to do it, in the STL chapter.
This is file IO.CPP from chapter eight,
of the exercise files.
You'll notice the C standard IO header at the top,
and I have got some constants here and a file name
and a string to write to the file.
The F open function is used to open a file.
It can open a file for read, write, append or a combination.
The first argument is a file name as a C string.
The second argument is the mode string.
The mode string is a string of characters
which controls how a file is opened.
Any of these characters in the mode string column
can be used or combined for opening a file.
In this case, we are opening the file in write mode,
so we are using a W. This creates a file for writing.
If the file exists it destroys the contents,
if the file doesn't exist it creates a new file.
And this is true for any of the modes
that include writing to a file.
They include writing to a file it does the reasonable thing
if the file exists and if it doesn't exist
it creates a new file.
Reopening a file for read,
its going to try and read the file from the start
and if the file doesn't exist it will simply fail.
We are opening this file for write
and we are going to create a new file because
it doesn't exist yet.
F open returns a file handle. The type which
is defined by a typed F in standard IO header,
and its always taken as a pointer.
We then loop it we call F puts with our string,
this is the literal C string with the new line,
and the second argument here you will notice
is the file handle.
Then we call Fclose with the file handle ,
and we open again this time in read mode
we are using F open in read mode
and we use F gets to get the contents of the file,
one line at a time.
F puts to write their buffer out to the standard out string
and standard out is a macro defined in a standard IO header
and its simply means the console ,
its like a file handle for the console.
And then we use F close to close the file and
remove to erase the file from the file system.
I'm going to go ahead and build and run this
and you can see it operating.
We write the file and then we read the file ,
then write each of the strings out the console
and we are done.
This is how to read and write a text file,
we will cover binary files in the next lesson.