首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C服务器中返回404error.html页

在C服务器中返回404error.html页
EN

Stack Overflow用户
提问于 2018-06-02 03:07:10
回答 1查看 1.6K关注 0票数 0

我用C语言编写了一个web服务器,根据URL中提供的请求,web服务器完全成功地检索到了相关的网页!下面是处理URL请求的代码部分!

代码语言:javascript
复制
if ( strncmp(reqline[1], "/\0", 2)==0 ) 
    reqline[1] = "/index.html";
    //If no file is specified, index.html will be opened by default  

strcpy(path, ROOT); 
strcpy(&path[strlen(ROOT)], reqline[1]); 
printf("file: %s\n", path); 

if ( (fd=open(path, O_RDONLY))!=-1 )    //If a html file is found
{
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
}
else { //If html file not found
    write (clients[n], "File not found", 15);      
}

当用户提供一个不存在的404error.html文件的网址而不是当前显示的文本“找不到文件”时,我想要显示我的index.html网页(在有html和其他html网页的文件夹中找到)。

EN

回答 1

Stack Overflow用户

发布于 2018-06-02 03:50:41

我不能编译或运行不完整的代码,但如果没有找到请求的文件,“猜测”将发送错误通知文件。"404error.html“文件必须存在于可用路径上。

代码语言:javascript
复制
if ( (fd=open(path, O_RDONLY))!=-1 ) {                  // If the file is found
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
    close(fd);                                          // add this
}
else if ( (fd=open("404error.html", O_RDONLY))!=-1 ) {  // Send the error file
    send(clients[n], "HTTP/1.0 200 OK\n\n", 17, 0); 
    while ( (bytes_read=read(fd, data_to_send, BYTES))>0 ) 
        write (clients[n], data_to_send, bytes_read);
    close(fd);                                          // add this
}
else {
    write (clients[n], "File not found", 15);           // tough luck, back to to you
}

我不知道clients[n]是什么,但你肯定知道。

源代码可以通过不重复传输代码来提高效率,但我将这留给您。这个答案是一个想法。

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

https://stackoverflow.com/questions/50649709

复制
相关文章

相似问题

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