【问题标题】:Linux C open() FailingLinux C open() 失败
【发布时间】:2016-02-24 09:17:47
【问题描述】:

我的文件 open() 一直失败。 程序接受文件名的参数。可执行文件就在我的测试文件“file.txt”旁边。

./runProgram file.txt 
ERROR - open() failed: Invalid argument

问题是参数是一个字符串,我可以 printf() 它就好了。所以我不确定为什么它是一个无效的参数......我正在尝试打开一个文件,以便获得系统的路径名限制。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int main(int argc, char **argv)
{
    printf("Pathname limit according to <limits.h> is: %i\n", PATH_MAX);

    int inputFD;//file descriptor to open the file

    //check and make sure that the user gave us the file name
    if(argc != 2)
    {
        fprintf(stderr, "ERROR - No file name argument!\n");
        return -1;
    }

    printf("%s\n", argv[1]);

    inputFD = open(argv[1], O_RDWR);
    if(inputFD == -1)
    {
        perror("ERROR - open() failed");
        return -1;
    }


    int fpcSize = fpathconf(inputFD, PATH_MAX);//return value from fpathconf

    if(fpcSize == -1)
    {
        perror("ERROR - open() failed");
        return -1;
    }

    printf("Path Size Limit: %i\n", fpcSize);

    return 0;
}

【问题讨论】:

  • 您确定您的open(),而不是您的fpathconf() 失败了吗?不知何故,您对两者都使用了相同的错误消息。

标签: c linux file path


【解决方案1】:

失败的不是您的open() 调用,而是您的fpathconf() 调用(可能是偶然的)产生了相同的错误消息。并且错误消息告诉您,因为您实际上在 fpathconf() 的参数中使用了错误的宏:fpathconf() 的宏都以 _PC_ 开头,PATH_MAX默认值最大路径大小,而不是该属性的键。关键宏被称为_PC_PATH_MAX

fpathconf(inputFD, _PC_PATH_MAX);

【讨论】:

  • 我知道我遗漏了一些东西......非常感谢你发现它!
猜你喜欢
  • 2019-04-19
  • 1970-01-01
  • 2013-04-03
  • 2020-04-03
  • 1970-01-01
  • 2012-08-11
  • 2012-02-23
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多