Reputation: 2069
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)
{
czekaj(0);
*adres = znak;
sygnal(1);
}
}
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");
fclose(plik);
.....
plik = fopen("./result","a");
if(plik != NULL)
{
while(znak != EOF)
{
wait(1); //Opuszczenie semafora
znak=*adres;
if(znak != EOF)
{
fputc(znak,plik);
signal(0);
}
}
}
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
Upvotes: 0
Views: 88
Reputation: 154127
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");
Upvotes: 1