c - 使用 C 中的文件描述符查找文件流的大小

标签 c http file-descriptor

作为一项学校作业,我正在用 C 语言编写一个简单的 HTTP 网络服务器。 我已准备好大部分代码,但 send()/write() 需要发送消息的长度。

这就是我挣扎的地方。 fseek() 不起作用,因此 ftell() 返回“非法搜索”errno。在确定方法并检索到正确的响应代码后,我使用 fprintf() 直接写入文件流。

static void response(FILE *response, int code, char *path, int fd)
{
    FILE *body;
    char *line = makestring(300) //Creates an empty string of size 300

    ... // Replace code in between with other code block

    if(code == 200){
        http_ok(response); //A function with fprintf's to write the headers.
        body = fopen(path, "w");

        while(!feof(body)){
            fgets(line, 300, body);
            fprintf(response, "%s\r\n", line);
        }

    fclose(body);
    }

    ... // Replace up to this point

fseek(response, 0L, SEEK_END);
int response_size = ftell(response);
rewind(response);

send(fd, response, response_size, 0);
}

现在,这是我的代码的简化版本,仅包括状态 200。 问题是响应正确返回,页面在浏览器中打开。但是,response_size 变量总是打印到 -1

现在继续处理状态代码 301 Moved Permanently,它根本不起作用。此代码可以替代两个“...”之间的其他 if 语句

...
if(code == 301){
    http_moved(response, path);
}
...

http 函数一般看起来像这样

void http_ok/moved(FILE *response)
{
    fprintf(response, "Correct codes and headers for the response type here\r\n")
    ...
    fprintf(response, "\r\n\r\n")
}

响应 FILE 使用 fdopen(sockfd, "w") 在套接字的文件描述符上打开,所以它不是普通的 fopen()。就我的理解而言,这意味着 fseek() 不会按预期工作。

至于问题本身,当我使用文件描述符时如何获得正确长度的 http 响应?

最佳答案

如果响应保证指向一个文件,我会使用:

#include <sys/stat.h>

struct stat st;

if (fstat(fileno(response)), &st) == -1) {
    /* handle error */
} else {
     response_size = (int)st.st_size;
}

关于c - 使用 C 中的文件描述符查找文件流的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25646376/

相关文章:

C 指针/HTTP 解析器(为什么我的代码不起作用)

http - 在 Heroku 上获取客户端的真实 IP 地址

c - 以非阻塞方式读取文本行

c++ - 从文件描述符实例化套接字对象的非侵入式方法

c - 在 OpenCV 中训练 SIFT 特征

c++ - C: main 没有找到,但它在那里 |编译错误

c - C 有类似 IDLE (python) 的东西吗?

php - 当人们 curl 我的网站时,我如何返回垃圾文本?

angular - POST 到 Angular/Tomcat 时的 403 状态码

c - 如何在管道的文件描述符上的线程 block 中进行 read() ?