fgetc始终返回-1

fgetc始终返回-1,c,visual-studio,C,Visual Studio,我试图一次读取一个文本文件中的一个字符,但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(

我试图一次读取一个文本文件中的一个字符,但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;
}
//file.txt


Hello World

您的读取循环位于以下位置之后: fseek(文件,0,SEEK_END); 声明

当您调用fgetc函数时,您已经到了文件的末尾


也许您可以添加fseek(文件,0,SEEK\u SET);ftell呼叫后?

使用
ftell
后,尝试
倒带
fseek
重新定位。谢谢,它可以工作,但为什么和如何工作?不要添加不相关的标签!C不是C++,因为FSEOD位置可能已经被设置为最后,因此,感谢快速响应,该解决方案工作。不幸的是,我没有足够的声誉来评价你的回答。。。