-
fread problems
Hello, I'm having problems with the fread function. I'm basically trying to read from a binary file. Here's my code :
Code:
// diskp is a pointer to the file to be read
int read_blocks(int start_address, int nblocks, void *buffer)
{
int f;
int err_num;
if ((fseek(diskp,start_address*BLOCK_SIZE,SEEK_SET)) != 0) // Seek to the point where read should start
{
fprintf(stderr,"Error in disk read : Unable to seek to given start location.\n");
return 0;
}
if ((f = (fread(buffer,BLOCK_SIZE,nblocks,diskp))) != nblocks) // Read from disk to buffer
{
if(feof(diskp) != 0)
{
fprintf(stdout,"End of file reached. %d Blocks read.\n",f);
return 1;
}
if((err_num = ferror(diskp)) != 0)
{
fprintf(stderr,"%s\n",strerror(err_num));
}
fprintf(stderr,"Error in disk read : Buffer write failed. %d\n",f);
return 0;
}
return 1;
}
Ok. So everytime I run this. I get an error saying "Operation not permitted", and 0 blocks are read. At first my intuition said that maybe I didn't have read permission on the file I was working on, but an ls, latter showed that :
Code:
total 44
-rwxrwxrwx 1 ythiel 16268 200 Mar 14 12:24 disk <--- file I am working on
-rwxr-xr-x 1 ythiel 16268 8136 Mar 14 12:24 disk_emu
-rw------- 1 ythiel 16268 3966 Mar 14 12:24 disk_emu.c
-rw------- 1 ythiel 16268 3968 Mar 14 12:23 disk_emu.c~
-rw------- 1 ythiel 16268 251 Mar 10 12:47 disk_emu.h
-rw------- 1 ythiel 16268 7323 Mar 10 12:47 disk_test.c
-rwx------ 1 ythiel 16268 8256 Mar 13 17:45 diskemu
-rw-r--r-- 1 ythiel 16268 0 Mar 14 12:36 dud
So I don't think that's the problem. Any ideas ?
-
> fread(buffer,BLOCK_SIZE,nblocks,diskp
Is your buffer really pointing at BLOCK_SIZE * nblocks bytes?
Normally, if you just want to read 'n' bytes, you just do
bytesRead = fread(buffer,1,nbytes,diskp);
-
I believe it is, here's how it's initialised :
Code:
data = (int*)calloc(1,(5*BLOCK_SIZE));
I then call my function using this :
Code:
read_blocks(10,5,data);
now the file I am working on is 80 bytes long, seperated into 20 blocks of 4 bytes (actually, sizeof(int) bytes), so even if those blocks are empty (which I don't think they are, anyways), I don't see how I would be getting an error.
Also, I actually do in fact have to seperate it into blocks of a certain given size. And although I can see how I could could just as well do this :
Code:
fread(buffer,1,BLOCK_SIZE*nblocks,diskp)
When I tried that, I got the same error.
Any other ideas ?
-
You'd have to post more code - like how some of those variables and constants are declared in main()
I take it diskp is a FILE* opened for reading binary data?
-
I feel so stupid. As it turns out, after discussing this with my TA this morning, I was opening my file with only write permission. Adding a little '+' to the whole thing solved the problem. Thank you for your time Salem.