我正在运行一个简单的程序来打开文件。有关操作系统和处理器的一些详细信息:
.Ubuntu 64bits
.Processor AMD Ryzen 7
每次我尝试执行时总是收到此错误:No such file or directory
已经安装了 sudo apt-get install lib32z1 但问题依然存在。这是C程序的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
>
void main(void)
{
char* filename = "~/Documents/Manipulation/addresses.txt";
printf("\nUsing fopen fuction");
FILE* arch = fopen(filename, "r");
if(arch == 0)
{
perror("fopen");
printf("\n arch is null");
exit(0);
}
else
{
printf("\n Arch is opened..");
}
}
一个重要的细节是我何时使用函数open("addresses", O_RDONLY)
效果很好。请参阅下面的代码:
int fd;
printf("\nUsing open fuction");
fd = open ("addresses", O_RDONLY);
if(fd == 0)
{
fprintf(stderr, "can't open %s: %s\n", filename, strerror(errno));
exit(1);
}
else
{
printf("\n Arch is opened..");
}
有人知道如何解决这个问题吗?
最佳答案
正如上面注释中所指出的,路径文字中的波浪号字符不会被翻译到用户的主目录中。您可能需要在 Linux 系统上执行的操作是检索当前用户主目录信息,如之前的解决方案 User home directory 中所述。 .
利用此解决方案,以下是代码的重构版本。
#include <unistd.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
int main(void)
{
struct passwd *pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
char filename[200];
strcpy(filename, homedir);
strcat(filename, "/Documents/Manipulation/addresses.txt");
printf("\nUsing fopen fuction");
FILE* arch = fopen(filename, "r");
if(arch == 0)
{
perror("fopen");
printf("\n arch is null");
exit(0);
}
else
{
printf("\n Arch is opened..");
}
return 0;
}
请注意添加的“unistd.h”和“pwd.h”包含文件。经过一些重构,以下是程序的测试执行。
@Vera:~/C_Programs/Console/LinuxFile/bin/Release$ ./LinuxFile
Using fopen fuction
Arch is opened..
尝试一下,看看它是否符合您的项目精神。
关于c - 函数 fopen(filename, "r") 在我的 Ubuntu 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75569655/