File Stuff

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

    FILE *fp;
    string  FilePath("c:\\test.txt");
    if((fp = fopen(FilePath.c_str(), "a")) == NULL)
    // do file operations here

 Copy a file

    string CopyFromPath("c:\\test.txt");
    string CopyToPath("c:\\test2.txt");
    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
    string oldname("c:\\test.txt");
    string newname("c:\\test2.txt");
    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.

 int error;

    error = rename(oldname.c_str(), newname.c_str());

    if (error)
        ... something went wrong... handle it.

Delete a file

   string file_to_delete("c:\\test2.txt");


Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>