c - 函数 fopen(filename, "r") 在我的 Ubuntu 上不起作用

标签 c linux function ubuntu pointers

我正在运行一个简单的程序来打开文件。有关操作系统和处理器的一些详细信息:

 .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/

相关文章:

c++ - GCC 编译器支持经典 C++ 吗?

python - 如何接受多个元素的列表作为命令行参数?

javascript - 在导致错误的 JavaScript 花括号中返回一个对象

c++ - 如何让 const char* 函数工作?

javascript - 如果单击某些 div,则不执行 keydown 函数

c - Xcode 4.5 - C 编程 - 内置控制台不允许两位数输入,但运行内置 exec 会

c - 为什么输入(换行)不会退出scanf?

c - 为什么它返回我段错误(核心转储)?

c - "Invalid operands to binary expressions"错误

linux - 每天在 bash 中提取文件行