【问题标题】:open() file does not exists when file actually exists当文件实际存在时,open() 文件不存在
【发布时间】:2016-06-05 21:55:28
【问题描述】:

我正在编写一个简单的 HTTP 服务器,当文件存在时,我得到一个文件不存在的返回值

printf("%s\n", html_path);
if ((fd = open(html_path, "r")) >= 0){ //file found

  stat(file_name, &st);
  file_size = st.st_size;
  printf("%d\n", file_size);
  while (read(fd, response, RCVBUFSIZE) > 0){

  }
}
else { //file not found
    strcpy(response, "404 File not found\n");
    send(clntSocket, response, 32, 0);
}

print语句是用来验证路径的,看起来是这样的:

/mounts/u-zon-d2/ugrad/kmwe236/HTML/index.html

请注意,此路径位于我们大学使用的服务器上。这是我命令pwd时显示的路径@

我已确认该文件存在。我的路径有问题吗?

【问题讨论】:

  • 观察到的第一件事:有没有可能混合使用 open 和 fopen? "r" 适合 fopen,因为 open 你会通过 O_RDONLY。
  • 你从哪里得到open函数?如果这应该是一个系统调用open(2),那么它有不同的原型,你应该写open(html_path, O_RDONLY)。或者,也许您想使用fopen(3)?无论如何,如果失败并不意味着该文件不存在:可能还有其他问题,例如您没有适当的访问权限。使用strerror(3) 打印错误的实际原因。

标签: c file file-exists


【解决方案1】:

open 没有第二个参数作为字符串。您将 open 与 fopen 的参数一起使用。 对于网络服务器 fopen、fprintf、fclose 是一个更好的选择,然后是更底层的打开、读取、...

干杯, 克里斯

【讨论】:

    【解决方案2】:

    打开文件时出错,但你不知道是因为你没有检查errno的值,所以找不到文件。

    else 部分,添加以下内容:

    else { //file not found
        // copy the value of errno since other function calls may change its value
        int err = errno;
        if (err == ENOENT) {
            strcpy(response, "404 File not found\n");
            send(clntSocket, response, 32, 0);
        } else {
            printf("file open failed: error code %d: %s\n", err, strerror(err));
        }
    }
    

    如果文件实际上不存在,您将正确处理错误。如果没有,您将打印一条错误消息,告诉您发生了什么。

    您还错误地调用了open。第二个参数是一个包含标志的int。要打开文件进行阅读,请使用O_RDONLY

    【讨论】:

      【解决方案3】:

      您需要检查程序在哪里执行,因为它会尝试从该位置打开相对路径。检查使用:

      char cwd[1024];
      getcwd(cwd, sizeof(cwd));
      puts(cwd);
      

      然后您可以使用以下方式连接您的路径:

      strncat(cwd, html_path, 100);
      

      你可能会发现你必须去一个目录或其他地方才能找到你正在寻找的文件。

      另请注意,如果您通过gdb 调试程序,它可能会从与您的常规构建位置不同的位置执行,这可能会使您更难发现错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-02
        • 2020-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多