The first thing to do is introduce some error checking.
Since you use the same file name for every file you read:
fp=fopen("p[i].gif","rb");
And you don't close it, that's going to give an error at some point.
But...what happens if the file doesn't exist?
fopen
will return a null, you will pass it to
fread
and you will get a segmentation fault...
You can start by replacing the fixed file name with the result from the
sprintf
call and that will help - but you do need to check the return value from
fopen
or you will have more problems later. And close your damn files when you have finished with them!