Tinyhttpd
Tinyhttpd copied to clipboard
cat函数在读取文件的字符数小于fget的单次读取数时出现的问题
问题
void cat(int client, FILE *resource)
{
char buf[1024];
fgets(buf, sizeof(buf), resource);
while (!feof(resource))
{
send(client, buf, strlen(buf), 0);
fgets(buf, sizeof(buf), resource);
}
}
cat 函数在读取长度小于 1024 的文件时,在第一次 fgets 后 resourse 就已经被设为 eof 了,因此也无法进入循环 send 了。
测试
test.txt
hello world
a.c
#include <stdio.h>
#define MAXLEN 20
int main() {
FILE *fp;
char str[MAXLEN];
fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("ERROR OPEN FILE");
return -1;
}
if (fgets(str, sizeof(str), fp) != NULL) {
puts(str);
}
if (feof(fp)) {
puts("eof");
} else {
puts("no eof");
}
fclose(fp);
return 0;
}
执行结果
