简体   繁体   中英

Regarding Storing Structure in file using read and write

I need to make the data in the structure as persistent ie wanted to store it in a file and need to read that character by character...For this i had written the below code...the below code is not working it is unable to write the structure into the file(character by character)... I needed that character by character

struct x *x1=(struct x*)malloc(sizeof(struct x));
x1->y=29;
x1->c='A';
char *x2=(char *)malloc(sizeof(struct x));
char *s=(char *)malloc(sizeof(struct x));
for(i=0;i<sizeof(struct x);i++)
{
    *(x2+i)=*((char *)x1+i);
}
fd=open("rohit",O_RDWR); 
num1=write(fd,x2,sizeof(struct x));
num2=read(fd,s,sizeof(struct x));
for(i=0;i<sizeof(struct x);i++)
     printf(" %d ",*(s+i));

I can use fread & fwrite...but i wanted to do that character by character...so i am using read & write(they are direct system calls rite)...i am unable to write into it my write function is showing error ie it is returning -1...Is there anything wrong in the above code...

Seeing as you tagged this as C++, I'll give you the C++ answer.

From what I can tell from your code you have a struct x1 such that

 struct { 
     int  y;
     char c;
 };

And you wish to serialise it's state to and from disk, to do this we need to create some stream insertion and stream extraction opterators;

//insertions
std::ostream& operator<<(std::ostream& os, const x& x1) {
     return os << x1.y << '\t' << x1.c;
}
//extration
std::istream& operator>>(std::istream& is, x& x1) {
     return is >> x1.y >> x1.c;
}

Now to serailise the state of an x we can do the following

x x1 { 29, 'A' };
std::ofstream file("rohit");
file << x1;

And to deserialise

x x1;
std::ifstream file("rohit");
file >> x1;

Here are two functions you can use if you want:

int store(char * filename, void * ptr, size_t size)
{
  int fd, n;

  fd = open(filename, O_CREAT | O_WRONLY, 0644);
  if (fd < 0)
    return -1;

  n = write(fd, (unsigned char *)ptr, size);
  if (n != size)
    return -1;

  close(fd);
  return 0;
}

int restore(char * filename, void * ptr, size_t size)
{
  int fd, n;

  fd = open(filename, O_RDONLY, 0644);
  if (fd < 0)
    return -1;

  n = read(fd, (unsigned char *)ptr, size);
  if (n != size)
    return -1;

  close(fd);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM