reading an int from a file with read()
I'm working on a C programming assignment where we are only allowed to use lower level file IO commands (so no fprintf()
or fscanf()
function calls) to read and write a file.
In one section of the code I write a string to a file of 128 characters and right next to it I write an integer. I am able to use pread
to read
the string of characters alright but I get a "bad address" error when I use pread
again to read the integer:
if(pread(heap, structure->str, STRING_MAX_LEN, 0) < 0)
{
return -1;
}
else
{
printf("read str\n");
}
if(pread(file, structure->size, 1, STRING_MAX_LEN + 1) < 0)
{
return 0;
}
else
开发者_运维技巧{
printf("read size\n");
}
Does anybody know what I'm doing wrong?
Is structure->size
an int*
? If it's just an int
then you'd need to pass its address with &
.
Edit: and as said by others, "1" is almost certainly not the number of bytes in your int, though it could be - you should probably use sizeof()
Try using sizeof
rather than hardcoding the size. Let the compiler work for you.
Second, the 2nd argument of pread
looks to be a pointer to the buffer you intend to fill. You're passing the int field itself (by value) — usually, the C compiler is more than happy to treat an int as a pointer. You need to pass the int field by reference, so that pread
has a pointer to the int it's supposed to fill with octets. You get the memory access violation (bad address) because the value of int field you're passing by value, treated as an address point to a memory location, you're not allowed to touch.
The first pread()
works because (I suspect) that structure->str
is either a char*
or an an array of chars, which will get treated as an pointer.
if ( pread(heap,structure->str,STRING_MAX_LEN,0) < 0 )
{
return -1;
}
else
{
printf("read str\n");
}
if ( pread(file,&(structure->size), sizeof(structure->size) , STRING_MAX_LEN + 1 ) < 0 )
{
return 0 ;
}
else
{
printf("read size\n");
}
You are passing a 1 as the size of the integer. Unless it is a char, you are doing it wrong.
What is structure->size
? What type?
EDIT
Since that you are in fact writing an int, you should use sizeof(int)
or sizeof(structure->size)
.
You should also pass the address to the variable, and not it's value, using the &
operator, so your line would be like:
if (pread(file, &structure->size, sizeof(structure->size), STRING_MAX_LEN + 1) < 0) {
return 0;
}
else {
printf("read size\n");
}
精彩评论