How to check if a file exists before creating a new file

前端 未结 9 897
我寻月下人不归
我寻月下人不归 2021-01-01 10:49

I want to input some contents to a file, but I\'d like to check first if a file with the name I wish to create exists. If so, I don\'t want to create any file, even if the f

相关标签:
9条回答
  • 2021-01-01 10:53

    The easiest way to do this is using ios :: noreplace.

    0 讨论(0)
  • 2021-01-01 10:54

    Try

    ifstream my_file("test.txt");
    if (my_file)
    {
     // do stuff
    }
    

    From: How to check if a file exists and is readable in C++?

    or you could use boost functions.

    0 讨论(0)
  • 2021-01-01 10:54

    Looked around a bit, and the only thing I find is using the open system call. It is the only function I found that allows you to create a file in a way that will fail if it already exists

    #include <fcntl.h>
    #include <errno.h>
    
    int fd=open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
    if (fd < 0) {
      /* file exists or otherwise uncreatable
         you might want to check errno*/
    }else {
      /* File is open to writing */
    }
    

    Note that you have to give permissions since you are creating a file.

    This also removes any race conditions there might be

    0 讨论(0)
  • 2021-01-01 10:56

    Try this (copied-ish from Erik Garrison: https://stackoverflow.com/a/3071528/575530)

    #include <sys/stat.h>
    
    bool FileExists(char* filename) 
    {
        struct stat fileInfo;
        return stat(filename, &fileInfo) == 0;
    }
    

    stat returns 0 if the file exists and -1 if not.

    0 讨论(0)
  • 2021-01-01 10:56

    As of C++17 there is:

    if (std::filesystem::exists(pathname)) {
       ...
    
    0 讨论(0)
  • 2021-01-01 10:58

    Assuming it is OK that the operation is not atomic, you can do:

    if (std::ifstream(name))
    {
         std::cout << "File already exists" << std::endl;
         return false;
    }
    std::ofstream file(name);
    if (!file)
    {
         std::cout << "File could not be created" << std::endl;
         return false;
    }
    ... 
    

    Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].

    A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.

    In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.

    0 讨论(0)
提交回复
热议问题