【问题标题】:if file doesn't exits create and write in C [closed]如果文件不存在,则在 C 中创建和写入 [关闭]
【发布时间】:2018-10-09 20:10:50
【问题描述】:

如果它不存在,我只想写“null”。如果它存在,我会写书名等不为空。所以我尝试了这段代码。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 30

int main() {
    FILE * shelfFile;
    //if file doesn't exist
    char start[MAX] = "NULL";
    if (!(shelfFile = fopen("shelf.txt", "r"))) {
        shelfFile = fopen("shelf.txt", "w");
        printf("In if block\n");
        fwrite(start, sizeof(char), MAX, shelfFile);
        fwrite("\n", sizeof(char), 1, shelfFile);
    }   
    fclose(shelfFile);

    system("PAUSE");
    return 0;
}

当我运行此代码时,该文件尚未创建并且 printf 也不起作用。很快它就不会进入 if 代码块。这有什么问题?

【问题讨论】:

    标签: c file if-statement fopen fwrite


    【解决方案1】:

    只需打开文件一次,即可写入(即"w" 模式)。如果文件不存在,则创建;如果它存在,它的内容将在打开时被销毁。

    有关更多信息,请参阅这张关于fopen 的方便表格。

    【讨论】:

    • 如果内容存在,我不想销毁它
    • @codergirrl:你检查过链接的表吗?
    • @codergirrl:那你想做什么?
    • @Acorn 如果它不存在,我只想写“null”。如果它存在,我会写书名等不为空。所以我尝试了这段代码。我希望我说清楚了。
    • @codergirrl:当你说“write”时,你指的是文件还是终端/屏幕/标准输出?请提供一个您想要达到的具体目标的示例。
    【解决方案2】:

    如果您想坚持使用标准 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 上编写此代码需要帮助,请告诉我。祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-05
      • 2012-04-08
      • 2016-06-04
      • 2012-05-10
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多