c - fgetc 总是返回 -1

标签 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("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(文件, 0, SEEK_END); 声明!!!

当您调用 fgetc 函数时,您已到达文件末尾!

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

关于c - fgetc 总是返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583696/

相关文章:

visual-studio - 用于单元测试的单独 Visual Studio 解决方案?

c - fprintf 语句中的\b 转义序列有问题..?

c - 将文件中的值插入链表时出现段错误

ios - 如何在Visual Studio中创建空白WinObjc项目?

windows - 建立cvhaartraining.lib

c++ win32 输出文本

ios - 如何在 iOS 中获得 C 函数崩溃?

c# - 如何从 unity C# 访问自定义 C 类型定义、枚举?

c - C 中的链表插入

c++ - 已经定义的类 C++