gpt4 book ai didi

c - 除非文件存在于 C 中,否则如何安全地写入文件?

转载 作者:行者123 更新时间:2023-12-02 03:23:27 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

FILE* f = fopen_unless_exists("example.txt");

if (f != NULL) {
fprintf(f, "foo bar baz\n");
} else {
// f should be NULL if example.txt already exists
fprintf(stderr, "Error: cannot write to file or file already exists");
}

我当然可以使用 one of the methods mentioned in a related question ,但正如对那里的答案的评论中所述,这将是一个竞争条件(具体来说, TOCTOU )。

什么是安全创建和写入文件的最简单方法,除非文件已经存在,并且不会产生竞争条件?

最佳答案

您必须使用 open(2) 系统调用和 O_EXCL|O_CREAT|O_WRONLY,然后对该描述符调用 fdopen(3) .

#include <sys/errno.h>
#include <fcntl.h>

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

int main(int argc, char *argv[]) {
char *program = argv[0];
char *filename = argv[1];

if (argc != 2) {
fprintf(stderr, "%s: expected a single file argument.\n", program);
exit(1);
}

int flags = O_EXCL|O_CREAT|O_WRONLY;
int mode = 0666;

int fd;
if ((fd = open(filename, flags, mode)) == -1) {
fprintf(stderr, "%s: cannot open %s with flags 0x%04X: %s\n",
program, filename, flags, strerror(errno));
exit(2);
}

FILE *fp = fdopen(fd, "w");
if (fp == NULL) {
fprintf(stderr, "%s: cannot fdopen file descriptor %d: %s\n",
program, fd, strerror(errno));
exit(3);
}

if (fprintf(fp, "12345\n") == EOF) {
fprintf(stderr, "%s: cannot write to %s: %s\n",
program, filename, strerror(errno));
exit(4);
}

if (fclose(fp) == EOF) {
fprintf(stderr, "%s: cannot close %s: %s\n",
program, filename, strerror(errno));
exit(5);
}

exit(0);
}

那些 open(2) 旗帜属于少数 guaranteed by POSIX .

这不能保证在远程文件系统上可靠地工作。特别是,NFS 打破了关于原子创建的 POSIX 规则。 [原文如此]

关于c - 除非文件存在于 C 中,否则如何安全地写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31690492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com