gpt4 book ai didi

c - 如果文件已经打开,fopen 是否返回 NULL 指针?

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:59 24 4
gpt4 key购买 nike

我假设如果文件已经打开,fopen 返回 NULL 指针。但它看起来 fopen 不会返回 NULL 以防文件已经在 "w" 模式下打开。下面是我用来尝试这个的代码,我没有收到任何错误。我尝试使用 mingw32 和 TDM-GCC-64 编译器。如果我没记错的话,如果文件已经打开,C++ 会报错。

#include<stdio.h>

int main()
{
FILE *fp1, *fp2;

fp1 = fopen("file1.txt", "w");
fp2 = fopen("file1.txt", "w");

if(fp2 == NULL)
{
printf("Error in opening file\n");
return(0);
}

// Edit: added following code to check the behavior if write operation
// is performed simultaneously

fputc('A', fp1);
fputc('M', fp1);
fputc('S', fp1);
fputc('B', fp2);

fclose(fp1);
fclose(fp2);

return 0;
}

编辑:添加了额外的代码以将一些数据写入 fp1fp2 并查看行为。如果执行,file1.txt 包含数据 BMS 并且似乎是正确的行为,fp1fp2 独立移动预期的。首先 AMS 使用 fp1 编写,然后使用 fp2A 替换为 B最终输出为 BMS

最佳答案

根据 C 标准 (7.19.3.8),它是实现定义的:

Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined.

最重要的是,由于其他原因不鼓励这样做,例如参见 SEI CERT C Coding Standard's FIO24-C recommendation :

Some implementations do not allow multiple copies of the same file to be open at the same time. Consequently, portable code cannot depend on what will happen if this rule is violated. Even on implementations that do not outright fail to open an already-opened file, a TOCTOU (time-of-check, time-of-use) race condition exists in which the second open could operate on a different file from the first due to the file being moved or deleted (see FIO45-C. Avoid TOCTOU race conditions while accessing files for more details on TOCTOU race conditions).

关于c - 如果文件已经打开,fopen 是否返回 NULL 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50114099/

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