Some basic file operations in C/C++, Windows operating system
Where possible, the following functions use standard library functions, which makes the code portable to other operating systems. Some of the examples use Windows API functions, because there are no standard library functions that directly do the same thing. Copying a file is an example. The standard library does not provide a single function to copy a file. (it is possible to copy files by reads and writes, but there is no “copy file” function that will do it in a single line of code.) It that case, I defer to the Windows API functions.
Open/Close a file
if((fp = fopen(FilePath.c_str(), "a")) == NULL)
// do file operations here
Copy a file
CopyFile(CopyFromPath.c_str(), CopyToPath.c_str(), false);
The CopyFile function is windows specific. This copies c:\test.txt to c:\test2.txt. If the output file (test2.txt) exists, it will be overwritten. If that is not desirable, the ‘false’ should be changed to ‘true’. When set to true, the last parameter specifies that the operation should fail (not happen) if the output file already exists.
Rename a file
rename("c:\\test.txt", "c:\\test2.txt"); // hard coded file names
rename(oldname.c_str(), newname.c_str()); // this does the same thing.
To see if the operation succeeded, evaluate what the function returns. If it is non-zero, the operation failed.
error = rename(oldname.c_str(), newname.c_str());
... something went wrong... handle it.
Delete a file