首页 > 解决方案 > 从文件中读取内容并将其存储到 C 中的 String

问题描述

我已经用 C 编写了一个简单的 http 服务器,现在正在尝试实现 HTML 文件。为此,我需要发送一个包含 HTML 文件内容的响应。我怎样才能做到最好?我是否逐行读取文件,如果是,如何将它们存储在单个字符串中?已经谢谢了!

标签: chttpweb

解决方案


这是一个按块读取文本文件的示例,如果文件很大,它将比逐行读取文件更快。

正如@tadman 在他的评论中所说,文本文件通常并不大,因此分块阅读它们不会对速度产生任何真正的影响,但网络服务器也可以提供其他文件——比如照片或电影(它们很大)。因此,如果您只打算读取文本文件,那么逐行读取可能会更简单(您可以使用 fgets 而不是 fread)但是如果您要读取其他类型的文件,那么以块的形式读取所有文件意味着您可以做到对所有人都一样。

然而,正如@chux 在他的评论中所说,阅读文本文件和二进制文件之间还有另一个区别。区别在于文本文件以文本模式打开:fopen(filename,"r"); 而二进制文件必须以二进制模式打开:fopen(filename,"rb"); Web 服务器可能会以二进制模式打开所有文件,因为 Web 浏览器无论如何都会忽略空格,但其他类型的程序需要知道该行是什么结局将是这样,它可以有所作为。

https://onlinegdb.com/HkM---r2X

#include <stdio.h>

int main()
{
    // we will make the buffer 200 bytes in size
    // this is big enough for the whole file
    // in reality you would probably stat the file
    // to find it's size and then malloc the memory
    // or you could read the file twice:
    // - first time counting the bytes
    // - second time reading the bytes
    char buffer[200]="", *current=buffer;
    // we will read 20 bytes at a time to show that the loop works
    // in reality you would pick something approaching the page size
    // perhaps 4096?  Benchmarking might help choose a good size
    int bytes, chunk=20, size=sizeof(buffer)/sizeof(char);
    // open the text file in text mode
    // if it was a binary file you would need "rb" instead of "r"
    FILE *file=fopen("test.html","r");
    if(file)
    {
        // loop through reading the bytes
        do {
            bytes=fread(current,sizeof(char),chunk,file);
            current+=bytes;
        } while (bytes==chunk);
        // close the file
        fclose(file);
        // terminate the buffer so that string function will work
        *current='\0';
        // print the buffer
        printf("%s",buffer);
    }
    return 0;
}

推荐阅读