gpt4 book ai didi

C fopen() 无法打开/tmp 中的文件

转载 作者:行者123 更新时间:2023-11-30 16:24:11 25 4
gpt4 key购买 nike

我正在学习tutorialspoint.com 上的基本 C 编程教程

我有以下程序,它在/tmp 中生成一个名为 test.txt 的文件:

#include <stdio.h>

int main() {

FILE *fp;

fp = fopen("/tmp/test.text", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);

return 0;

}

然后我有第二个程序,它只是尝试打开该文件进行阅读:

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

int main() {

FILE *fp = NULL;

fp = fopen("/tmp/test.txt", "r");

if (fp == NULL) {
printf("NULL!!!\n");
}

printf("%s\n", strerror(errno));

fclose(fp);

return 0;

}

但是,当我尝试运行打开该文件的程序时,我得到以下输出:

NULL!!!
No such file or directory
Segmentation fault

如果我修改代码以指向主目录中的同一文件,则它可以正常工作。似乎,由于某种原因,我无法打开/tmp 目录中的文件(通过 fopen)...为了清楚起见,我可以更改为/tmp 并 cat test.txt 的内容文件就好了。权限看起来也很正常,664,我的用户作为所有者和组。

我能想到的可能与我的系统有关的唯一其他细节是我使用的是 Elementary OS Juno,我使用的是 g++ 7.3.0(clang 也给出了相同的结果),并且我有单独的加密我的操作系统根目录和主目录的分区...

有什么想法可能导致这种情况吗?

最佳答案

这只是由不正确的文件扩展名引起的,如 @yano 指出的 .txt 与文本

关于C fopen() 无法打开/tmp 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53698409/

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