简体   繁体   English

在c中的HTTP响应中使用fread()提供text / html文件

[英]serve text/html file with fread() in HTTP response in c

When building a HTTP response, I need to read the file I want to serve in memory. 在构建HTTP响应时,我需要读取我想要在内存中提供的文件。

For binary files, like jpeg , I use 对于二进制文件,比如jpeg ,我使用

//Setup and other headers omitted
stat(file, &fileStat);
int fileSize=fileState.st_size
sprintf(headerBuffer, "content-length: %u\r\n\r\n", fileSize)
fread(fileBuffer, fileSize, 1, filePtr);
//combine headerBuffer and fileBuffer, then send to socket

However I don't know how to deal with text files, like html . 但是我不知道如何处理文本文件,比如html I'm confused about these two things: 我对这两件事感到困惑:

  • Is the content-length still the file size or strlen(whole file as a string) ? content-length仍然是文件大小或strlen(whole file as a string) or are they the same thing? 或者他们是一样的吗?
  • Can I still use fread() to load an text file or do I read it line by line with fgets() ? 我仍然可以使用fread()加载文本文件,还是我用fgets()逐行阅读? I thought fread() was only for reading binary files, wasn't it? 我以为fread()只用于读取二进制文件,不是吗?

Content-length is the full length of the entity sent in the response. Content-length是响应中发送的实体的全长。 If you're sending a file, it's the file size (unless you're applying any content encoding like gzip, in that case it's the size of the file after encoded). 如果您要发送文件,那就是文件大小(除非您正在应用任何内容编码,如gzip,在这种情况下,它是编码后文件的大小)。

The concept of "letters" doesn't enter the picture and it wouldn't make sense. “字母”的概念不会进入图片,也没有意义。 HTTP is not used just to transfer text and what constitutes a letter is in itself problematic (eg encoding, Unicode version if applicable, ...). HTTP不仅用于传输文本,而构成字母的内容本身也存在问题(例如编码,Unicode版本,如果适用,......)。

Finally, you can of course, use fread instead of fgets . 最后,您当然可以使用fread而不是fgets There's no reason to send the response line-by-line. 没有理由逐行发送响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM