Jump to content

need help in unix c programming

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
mjumrani

mjumrani

    Newbie

  • Members
  • Pip
  • 1 posts
hey guys.
im currently trying to make a program in unix (redhat, compiling the .c file using gcc) and i need urgent urgent help.

i need to save objects of structures in a file but they dont seem to be saving properly. ive been on it for a whole day now. dunno why i cant do it.
when i try to read, it reads the first search i give it but after that i start getting garbage

here is the structure(names of variables omitted)

struct Employee_Details
{ char [20]
long int
float
char [20]
time_t
}emp,temp;

the rest of the relevant code to add is here,

recv(sd,&emp,sizeof(emp),0);
fd=open("DB.txt",O_RDWR|O_CREAT,0766);
lseek(fd,0,SEEK_END);
write(fd,&emp,sizeof(emp));
send(sd,"Added",6,0);

here is the code to read the file

fd=open("DB.txt",O_RDWR|O_CREAT,0766);
recv(sd,&emp,sizeof(emp),0);
lseek(fd,0,SEEK_SET);
while(flag) /* flag=1*/
{ read(fd,&temp,sizeof(temp));
if(temp.INT_MEMBER==emp.INT_MEMBER)
{ flag=0;
send(sd,&temp,sizeof(temp),0);
lseek(fd,-(sizeof(temp)),SEEK_CUR);
temp.TimeStamp=time(NULL);
write(fd,&temp,sizeof(temp));
}
}

please help me out

#2
sea

sea

    Newbie

  • Members
  • Pip
  • 7 posts
Ah, I had this same problem a year ago or so. It turns out that structs in C are not arranged in memory like you define them. Your compiler actually rearranges the members of the struct to fit memory better.
See this article for more information:
Data structure alignment - Wikipedia, the free encyclopedia
Basically, you will need to pad your structs by including extra data elements so that the compiler does not see the need to rearrange parts of it.
I am not so sure right now because I'm very sleepy, but I think it would be:
struct Employee_Details
{
        char [20] c; // Has a size of 20 bytes.
        char [20]; //Has a size of 20 bytes.
        long int li; //Has a size of 4 bytes.
        float f; //Has a size of 4 bytes.
        time_t; //Has a size of 4 bytes, or it could be 8 bytes too..depending on the implementation.
}temp;
You want to be putting all of the members with the same sizes together, and keeping stuff at multiples of 2. I could be wrong with this struct though.