如果您想坚持使用标准 C,Acorn 的答案是正确的。据我所知,测试文件是否存在归于操作系统特定的 API。
在 Windows 上,您可以编写函数来测试文件是否存在,方法是将文件名传递给 GetFileAttributesFunction,如 here 所示。一旦你有了它,你所要做的就是编写函数来有条件地创建文件,如果它不存在的话。
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
void createFile(const char *filename) {
const HANDLE newFile = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (newFile == INVALID_HANDLE_VALUE) {
fprintf(stderr, "[Error]: Failed to open file: %s\n", filename);
exit(EXIT_FAILURE);
}
}
int FileExists(const char *filename) {
const DWORD fileAttributes = GetFileAttributes(filename);
if (fileAttributes == 0xFFFFFFFF)
return 0;
return 1;
}
void ConditionallyCreateFile(const char *filename) {
if (!FileExists(filename))
createFile(filename);
}
int main()
{
const char *filename = "test-file.txt";
printf("File exists: %d\n", FileExists(filename));
ConditionallyCreateFile(filename);
printf("File exists: %d\n", FileExists(filename));
return EXIT_SUCCESS;
}
当我第一次运行代码时,这是输出:
File exists: 0
File exists: 1
然后第二次:
File exists: 1
File exists: 1
话虽如此,但我要指出,如果您使用的是 Win32 API,那么您几乎可以肯定使用的是 Microsoft 编译器,因此您可以使用 C++ 编写相同的代码,我建议您这样做。这就是它的样子:
#include <Windows.h>
#include <iostream>
#include <iomanip>
#include <string>
namespace FS {
void CreateFile(const std::string& filename) {
const auto newFileHandle = ::CreateFile(filename.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (newFileHandle == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to create new file...\n";
exit(EXIT_FAILURE);
}
}
bool FileExists(const std::string& filename) {
const auto fileAttributes = ::GetFileAttributes(filename.c_str());
if (fileAttributes == 0xFFFFFFFF)
return false;
return true;
}
void ConditionallyCreateFile(const std::string& filename) {
if (!FileExists(filename))
FS::CreateFile(filename);
}
}
int main()
{
const std::string filename = "test-file.txt";
std::cout << std::boolalpha << "File exists: " << FS::FileExists(filename) << '\n';
FS::ConditionallyCreateFile(filename);
std::cout << "File exists: " << FS::FileExists(filename) << '\n';
return EXIT_SUCCESS;
}
如果我删除之前创建的test-file.txt 并再次运行程序,输出如下:
File exists: false
File exists: true
然后第二次:
File exists: true
File exists: true
总而言之,在创建文件之前确定文件是否存在是操作系统特定的任务。我假设您使用的是 Windows,因为从统计上讲,这是最有可能的情况,但是如果您在 Linux 上编写此代码需要帮助,请告诉我。祝你好运