Sobes.tech
Junior — Middle

What methods can ensure the creation of a file only if it does not already exist?

sobes.tech AI

Answer from AI

In C/C++, ensuring the creation of a file only if it does not exist can be achieved in several ways:

  1. Using the O_CREAT | O_EXCL flag when opening a file with the open system call (POSIX). The O_EXCL flag guarantees that the file will only be created if it does not already exist; otherwise, the call will fail with an error.
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int fd = open("file.txt", O_CREAT | O_EXCL | O_WRONLY, 0644);
if (fd == -1) {
    perror("File already exists or error");
} else {
    // File successfully created
    close(fd);
}
  1. In the C++ standard library, you can check for the existence of a file using <filesystem> (since C++17) and create the file if it does not exist:
#include <filesystem>
#include <fstream>

namespace fs = std::filesystem;

if (!fs::exists("file.txt")) {
    std::ofstream ofs("file.txt");
    // file created
}
  1. In C, you can first check for the existence of a file using fopen in read mode, and if the file is not found, open it for writing. However, this approach is not atomic and may lead to race conditions in multithreaded environments.

Thus, the most reliable method is to use open with the O_CREAT | O_EXCL flags for atomic creation of a file only if it does not exist.