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

前端 未结 9 907
我寻月下人不归
我寻月下人不归 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: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 
    #include 
    
    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

提交回复
热议问题