我正在编写一个简单的 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);
}
打印语句是为了验证路径,看起来是这样的:
/mounts/u-zon-d2/ugrad/kmwe236/HTML/index.html
请注意,此路径位于我们大学使用的服务器上。这是我命令 pwd
我已确认该文件存在。我的路径有问题吗?
最佳答案
打开文件时出错,但您不知道这是因为未找到文件,因为您没有检查 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
。
关于c - 当文件实际存在时 open() 文件不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588102/