Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cat函数在读取文件的字符数小于fget的单次读取数时出现的问题 #31

Open
freakkid opened this issue Jan 25, 2019 · 0 comments

Comments

@freakkid
Copy link

freakkid commented Jan 25, 2019

问题

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;
}

执行结果

image

freakkid added a commit to freakkid/Tinyhttpd that referenced this issue Jan 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant