C File read getchar yields random EOF after 32KB

I was tasked to make a file copy over ipc shared memory. The problem is that getc randomly yeilds EOF after 32k char.

FILE* file;
int znak;

file = fopen("./source","r");

if(file != NULL)
    while(feof(file) == 0)
        znak = getc(file);

        if(znak != EOF)
            *adres = znak;


    wait(0);        //Wait for your turn
    *adres = EOF;
    signal(1);      //Let other process go

Writing part as requested

int znak
FILE *plik;
plik = fopen("./plik_klient", "w");


plik = fopen("./result","a");

if(plik != NULL)
    while(znak != EOF)

        wait(1);        //Opuszczenie semafora


        if(znak != EOF)



As a result of work other process reads the info and writes it into file.

-rw-r--r--. 1 ficekba inf-17   32769 01-11 21:15 result
-rw-r--r--. 1 ficekba inf-17 1000000 01-11 21:13 source

As you can see result file has exactly 32k

1 answer

  • answered 2018-01-11 20:35 chux

    Code uses char znak when int znak is best.

    getc() returns an int in the range of unsigned char and EOF. This is typically 257 different values: [-1 ... 255]. When code read the file source and may return a 255 and assigns that to a char znak, znak has the value of -1 which matches EOF in this case. This fools code into thinking copying is done. and so may end up with a rump result file.

    Use int znak.

    Also open the file in binary mode is source may be a binary file.

    // file = fopen("./source","r");
    file = fopen("./source","rb");