开发者

Read structure contents using read() system call

开发者 https://www.devze.com 2023-02-20 10:27 出处:网络
#include \"common.h\" #include <string.h> struct buffer { int no; char name[20]; }; int main() { struct buffer buf;
#include "common.h"
#include <string.h>

struct buffer
{
   int no;
   char name[20];
};

int main()
{
   struct buffer buf;
   struct buffer read_buf;
   int fd;

   if((fd = open("read_write.txt",O_CREAT|O_RDWR,S_IRUSR|S_IWUSR)) < 0)
   {
      PRINT_ERROR(errorbuf);
   }

   buf.no = 10;
   strcpy(buf.name,"nitin");

   if(wr开发者_JAVA百科ite(fd, &buf, sizeof(struct buffer)) < 0)
   {
      PRINT_ERROR(errorbuf);
   }

   printf("Written successfully\n");

   /* Add code here to read the content of the structure into 'read_buf' */

   exit(0);
}

common.h

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

char errorbuf[20];

#define PRINT_ERROR(errorbuf) \
   do \
   { \
      sprintf(errorbuf,"%s:%d",__FILE__,__LINE__); \
      perror(errorbuf); \
      exit(-1); \
   }while(0);

I have written a structure into the file. But i am getting confused on how to retrieve each element of the structure written earlier into the object 'read_buf'. Kindly tell me how to do this.

Thanks


lseek(fd,0,SEEK_SET);
read(fd,&buf,sizeof(struct buffer);

Will work, but there are some other things you will have to worry about.

  • This is not portable.
  • You will have to worry about structure packing on different builds.
  • You will have endian problems cross platform.
  • Windows you may need O_BINARY.

It is nearly always better to repackage to structure in to a known format (with known endianess) so that you can reliably read the data back.


You read it back like this:

ssize_t bytes_read = read(fd, &buf, sizeof buf);
if(-1 == bytes_read)
    ; // handle read error
if(sizeof buf != bytes_read)
    ; // handle incomplete read


Writing/reading binary structures to/from files is not portable (depending on the platform architecture, structure padding etc). To make your program robust, you can use something like XDR.

0

精彩评论

暂无评论...
验证码 换一张
取 消