File exists, but open file still always returns -1

后端 未结 1 1210
情深已故
情深已故 2021-01-28 05:12

File \"~/workspace/Test.txt\" does exist, but fd always returns -1. Can somebody please give a hint as to what is wrong with the code? Thanks.

 int fd = open(\"~         


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-28 06:10

    (Assuming your OS is some Posix like Linux)

    The ~ should be expanded. Usually the shell expands it. But open wants a real file path.

    You could try:

    std::string fname (getenv("HOME"));
    fname += "/workspace/Test.txt";
    int fd = open(fname.c_str(), O_RDONLY);
    if (fd<0) {
       std::cerr << "failed to open " << fname 
                 << " : " << strerror(errno) << std::endl;
       return false;
    }   
    

    See glob(7), wordexp(3), getenv(3), strerror(3), open(2), environ(7)

    Read Advanced Linux Programming

    0 讨论(0)
提交回复
热议问题