File Stuff

Some basic file operations in C/C++, Windows operating system

Summary

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)
        return;
    // do file operations here
    fclose(fp);

 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

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

			

Leave a Reply

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