首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C,stat()的问题

C,stat()的问题
EN

Stack Overflow用户
提问于 2013-09-09 05:14:23
回答 2查看 190关注 0票数 0

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

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

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

然后服务器程序接收相同的东西。我有两个printf()来确认我正在正确地解析文件路径并查看完整的路径。它的产出如下:

代码语言:javascript
复制
File path = '/Makefile'
Full path = '~/asimes2/hw2/Makefile'
NOT FOUND!

Makefile确实存在于~/asimes/hw2中。以下是代码:

代码语言:javascript
复制
// 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");
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-09 05:18:03

我的回答只是用文件名来解决你的问题。

shell解释如下:~/asimes2/hw2/Makefile

它不是使用~传递给stat()的有效文件名

您应该能够将领先的~替换为某些链接/home/或实际主目录所在的任何位置。

试试这个:

代码语言:javascript
复制
char* fullPath = malloc((80+strlen(filePath))*sizeof(char));
strcpy(fullPath, "/home/ubuntu/asimes2/hw2");
strcat(fullPath, filePath);
printf("Full path = '%s'\n", fullPath);
票数 3
EN

Stack Overflow用户

发布于 2013-09-09 05:22:47

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

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

您也许应该使用一些HTTP服务器库,比如碳酸根

而且您至少应该使用errno来调试syscall故障,所以代码

代码语言:javascript
复制
  if (stat(fullPath, &fileStat) == -1) 
      printf("%s NOT FOUND! %s\n", fullPath, strerror(errno));

也许色度(2)会让你感兴趣。读高级Linux编程

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18691844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档