0

我以前从未使用stat()过,也不知道出了什么问题。

我有一个接受 GET 请求并解析文件路径的服务器程序。我在发送 GET 请求的同一目录中也有一个客户端程序。服务器程序正在接受 GET 请求并正确解析文件路径。两个程序所在目录的路径是:~/asimes2/hw2/

如果我有客户端程序发送:GET /Makefile HTTP/1.0\r\n\r\n

然后服务器程序收到同样的东西。我有两个printf()s 来确认我正在正确解析文件路径并查看完整路径。它输出:

File path = '/Makefile'
Full path = '~/asimes2/hw2/Makefile'
NOT FOUND!

Makefile确实存在于~/asimes/hw2. 这是代码:

// Alex: Parse the PATH from the GET request using httpGet
char* filePath, * pathStart = strchr(httpGet, '/');
if (pathStart != NULL) {
    // Alex: Increment to the first '/'
    httpGet += (int)(pathStart-httpGet);

    // Alex: Assuming " HTTP" is not a part of the PATH, this finds the end of the PATH
    char* pathEnd = strstr(httpGet, " HTTP");
    if (pathEnd != NULL) {
        int endLoc = (int)(pathEnd-httpGet);
        filePath = (char*)malloc((endLoc+1)*sizeof(char));
        strncpy(filePath, httpGet, endLoc);
        filePath[endLoc] = '\0';
    }
    else errorMessageExit("The GET request was not formatted as expected");
}
else errorMessageExit("The GET request was not formatted as expected");
printf("File path = '%s'\n", filePath);

char* fullPath = (char*)malloc((14+strlen(filePath))*sizeof(char));
strcpy(fullPath, "~/asimes2/hw2");
strcat(fullPath, filePath);
printf("Full path = '%s'\n", fullPath);

struct stat fileStat;
if (stat(fullPath, &fileStat) == -1) printf("NOT FOUND!\n");
else printf("HOORAY\n");
4

2 回答 2

3

我的回答仅解决您的文件名问题。

外壳解释了这一点:~/asimes2/hw2/Makefile

传递给 stat() 的文件名无效~

您应该能够用~链接/home/或实际主目录所在的任何位置替换前导。

尝试这个:

char* fullPath = malloc((80+strlen(filePath))*sizeof(char));
strcpy(fullPath, "/home/ubuntu/asimes2/hw2");
strcat(fullPath, filePath);
printf("Full path = '%s'\n", fullPath);
于 2013-09-09T05:18:03.667 回答
2

您需要 glob 路径名,请参阅glob(7)。您也许可以使用wordexp(3)来扩展~$ ...

HTTP 服务器通常有一些可配置的文档根,也许/var/www。然后将 URL 路径名/Makefile转换为/var/www/Makefile

您也许应该使用一些 HTTP 服务器库,例如libonion

并且您应该errno至少在系统调用失败时用于调试目的,所以代码

  if (stat(fullPath, &fileStat) == -1) 
      printf("%s NOT FOUND! %s\n", fullPath, strerror(errno));

也许chroot(2)可能会让您感兴趣。并阅读高级 Linux 编程

于 2013-09-09T05:22:47.637 回答