gpt4 book ai didi

C、stat() 的问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:01:40 24 4
gpt4 key购买 nike

我以前从未使用过 stat(),我不确定哪里出了问题。

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

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

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

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");

最佳答案

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

shell 对此进行解释:~/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);

关于C、stat() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com