- [Tutor] Let's take a quick look at how to create,
rename and delete files using the C++ Standard Library.
Here's working.cpp from chapter eight
of the exercise files.
We'll start by creating a file.
So I'm going to give it a file name.
We just call it file1,
and I will open the file in write mode,
file handle,
fopen
and the file name
and write mode.
And now that the file has been opened in write mode,
of course, if the file didn't exist,
the file will be created
and if file did exist, it will be empty.
It'll be overwritten with an empty file.
And so we'll just go ahead and close this now
because we have our file
and I'll just puts Done.
Like that.
And now when I build and run this,
you notice it says Done.
Now, how do I find my file?
Where is my file?
Well, on a Mac in Xcode,
you can control click on your result over here,
your working result,
and say Show in Finder.
And you'll notice if I control click up here,
I get the whole path.
See it's a crazy path.
This would be very hard to find on your own,
and that's why we have that Show in Finder over here.
And so here's our object file, it's our executable.
And here is the file that we just created.
And if I bring up the file info,
you'll notice that it is zero bytes.
It is an empty file.
Now, if I want to find the file on a PC,
here I have the same code in visual studio.
And you'll notice if I come over here to PowerShell
and I typed dir in my debug directory,
you'll notice I don't have any executable or anything
until I compile.
So I come back over here to visual studio
and I compile
using F7.
Now, when I type dir on my PowerShell,
you'll notice I have my executable working.exe,
and I can just say working.exe like this,
and it runs it.
And now when I type dir,
you'll notice
that there I have the file, file zero.
So it shows up right there in my debug directory
with my executable.
So now that we've found the file,
let's go ahead and rename it.
And so instead of opening it and closing it at this point,
what I'm going to do
is I'm going to create another file name.
And now I'm going to rename the file.
I'm going to say, rename
from the old file name, fn1,
to the new file name, fn2.
And I'll go ahead and I'll run this.
And now when I come out to finder,
you'll notice that I have file2 here instead of file1.
And if I want to remove the file altogether,
I now just have file2,
I can say remove instead of rename.
And when I build and run this
and come out here to finder,
you'll notice that my file is gone from my debug directory.
You'll have the same result on your windows PCs as well.
Both rename and remove
return zero on success or a non-zero value
if there's an error,
we'll look at how to read the return to error codes
in the lesson on handling system errors.
It's relatively simple to create,
delete and rename files using the C++ Standard Library,
and this is how you do that.