1

你如何制作一个文件,但前提是它不存在?像.. 我想读取一个文本文件,但如果它不存在,我想创建一个带有一些默认文本的文件。

我可以很容易地使用默认文本创建文件。如果它已经存在,我可以附加或覆盖它。

但如果它已经包含一些文本,我想从中读取。不要写给它。就像您可能使用点文件或配置文件一样,在文件丢失的情况下设置默认配置。

这对于 Python 来说非常简单,但我正在尝试过渡到 C,而且它比我预期的更具挑战性。


所以到目前为止,我的功能基本上看起来像这样。文本只是真实文本的占位符。

main() {
    FILE *fp;

    fp = fopen("./filename.txt", "w");
    fprintf(fp, "some default text\n");
    fclose(fp);
}

所以只是为了澄清:如果./file.txt已经存在,它不应该被写入。应该从中读取。

例如,当我说“读取”时,它可以打印到stdout或存储在数组中,但这可能超出了问题的范围。

4

2 回答 2

4

考虑到您的示例,有两个主要错误:

  1. 您不检查结果,fopen因此您不知道您的文件是否已成功打开(这是答案的关键)。
  2. printf函数直接打印到stdout,您必须使用fprintf一个打印到您的配置文件。

我提出以下建议:尝试检查fopen您的配置文件(例如./filename.txtr并检查此调用的结果。成功完成后,fopen返回一个FILE指向您现有配置文件的指针。如果文件不存在,则fopen返回NULL并将 errno 设置为ENOENT. 在这种情况下,您可以创建一个新的配置文件并将默认配置写入其中。

请参阅man 3相应文档部分。

更新

这是提案的 PoC

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main() {
    FILE *fp = fopen(".rc", "r");
    if (!fp)
        switch (errno) {
            case ENOENT:
                fprintf(stderr, "No config found, creating the default one\n");
                fp = fopen(".rc", "w");
                if (!fp) {
                    perror("Failed to create default config: ");
                    return EXIT_FAILURE;
                }
                /* write default config here */
                break;
            default:
                perror("Failed to open existing config: ");
                return EXIT_FAILURE;
        }

    /* read existing config here */
    return EXIT_SUCCESS;
}
于 2019-03-20T09:33:35.467 回答
0

在打开文件之前使用stat 。如果 stat 成功则文件存在,如果不存在,请检查 errno 中的 ENOENT。

例子

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
    struct stat file_infos;
    char file_path[] = "/whatever"
    if (stat(file_path, &file_infos) != 0)
    {
        if (errno == ENOENT)
        {
            // Do whatever when the file wasn't found
        }
        else
        {
            // Error accessing the file, check the errno for more infos
        }
    }
    else
    {
        // File exists, do whatever you like with it.
    }
}

享受 :)

于 2019-03-20T09:48:05.470 回答