开发者

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

开发者 https://www.devze.com 2023-04-07 04:42 出处:网络
When building a HTTP response, I need to read the file I want to serve in memory. For binary files, like jpeg, I use

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

精彩评论

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

关注公众号