从文件读取内容并将其存储到C中的String

时间:2018-10-29 21:27:18

标签: c http web

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

1 个答案:

答案 0 :(得分:1)

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

正如@tadman在评论中所说,文本文件通常并不大,因此以块的形式读取它们不会对速度产生任何实际的影响,但是Web服务器也可以提供其他文件-例如照片或电影(很大) 。因此,如果您只打算读取文本文件,那么逐行读取可能会更简单(可以使用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;
}