繁体   English   中英

关于使用读写在文件中存储结构

[英]Regarding Storing Structure in file using read and write

我需要使结构中的数据持久化,即想将其存储在文件中并需要逐个字符地读取该字符...为此,我编写了以下代码...以下代码无法正常工作将结构写入文件(一个字符一个字符)... 我需要一个字符一个字符

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));

我可以使用fread和fwrite ...但是我想逐个字符地执行该操作...所以我正在使用读写功能(它们是直接的系统调用rite)...我无法向其中写入我的write函数是显示错误,即它返回-1 ...上面的代码中是否有任何错误...

看到您将其标记为C ++后,我将为您提供C ++答案。

从我可以从你的代码告诉你有一个struct x1这样

 struct { 
     int  y;
     char c;
 };

您希望将其状态序列化到磁盘和从磁盘进行序列化,为此,我们需要创建一些流插入和流提取提出者;

//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;
}

我们serailise的状态x ,我们可以做以下

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

并反序列化

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

如果需要,可以使用以下两个功能:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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