Search code examples
cfilecharsymbolsfgetc

reading from a file . C


I want to read this symbols with fgetc() ( I cant copy it, here link to file.txt )

This file is 2-byte long and its binary dump is 1A 98.

fgetc() cant read it and return -1. Please help((

for (int k = 0; k < fileSize; k++)
{
    buffer[k] = (unsigned char) fgetc(f);
}

Picture of this symbols:
Picture of this symbols

Maybe something with character encoding?


Solution

  • Your file contains 0x1A, which means EOF and reading it will stop reading when the file is opened in text mode.

    Try opening your file in binary mode.

    Here is a test code:

    #include <stdio.h>
    
    int main(void) {
        const char *fileName = "codeText.txt";
        FILE* fp;
        int input;
    
        fp = fopen(fileName, "r");
        if (fp==NULL) return 1;
        puts("text mode:");
        while((input = getc(fp)) != EOF) printf("%02X\n", (unsigned int)input);
        fclose(fp);
    
        fp = fopen(fileName, "rb");
        if (fp == NULL) return 1;
        puts("binary mode:");
        while((input = getc(fp)) != EOF) printf("%02X\n", (unsigned int)input);
        fclose(fp);
    
        return 0;
    }