簡體   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