繁体   English   中英

fgetc 总是返回 -1

[英]fgetc always return -1

我试图从文本文件中一次读取一个字符,但 fgetc 从一开始就返回 -1,这意味着永远不会进入循环内部。 fileSize 在运行时为 11,并且不会显示任何错误。

//main.c

char *buffer = NULL;

char* readFile(const char *path) {
    FILE *file;
    file = fopen(path, "r");

    if (file == NULL) {
        perror(path);
        printf("Error: %d \n", errno);
        return "Error";
    }


    //get size of file.
    fseek(file, 0, SEEK_END);
    size_t fileSize = ftell(file); 

    //allocate sizeof file +1.
    char *buffer = (char *)malloc((fileSize +1) * sizeof(char));

    //read file into string
    int c;
    int i = 0;
    while((c = fgetc(file)) != EOF) {
        buffer[i] = (char)c;
        ++i;
    }
    buffer[i] = '\0';

    fclose(file);

return buffer;
}

void freeMem(void) {
    free(buffer);
}
int main(void) {
    const char *path = "C:\\Programmering\\TestReader\\syntax\\file.txt";
    char *cStr = readFile(path);

    //freeMem();
    system("pause");
return 0;
}

//文件.txt

你好,世界

您的读取循环位于您之后: fseek(file, 0, SEEK_END); 陈述!!!

当您调用 fgetc 函数时,您处于文件末尾!

也许你可以添加 fseek(file, 0, SEEK_SET); 在 ftell 电话之后?

暂无
暂无

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

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