开发者

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.

For binary files, like jpeg, I use

//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

Howeve开发者_如何学编程r I don't know how to deal with text files, like html. I'm confused about these two things:

  • Is the content-length still the file size or 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()? I thought fread() was only for reading binary files, wasn't it?


Content-length is the full length of the entity sent in the response. 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).

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 (e.g. encoding, Unicode version if applicable, ...).

Finally, you can of course, use fread instead of fgets. There's no reason to send the response line-by-line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜