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

标签 c++ c data-structures struct

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

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...但我想逐个字符地执行该操作...所以我正在使用 read 和 write(它们是直接系统调用仪式)...我无法写入它write 函数显示错误,即它返回 -1...上面的代码有什么问题吗...

最佳答案

如果需要,您可以使用以下两个函数:

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

关于c++ - 关于使用读写在文件中存储结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13117231/

相关文章:

c++ - Portaudio 不会使用 macports GCC 4.8 进行编译(-arch 命令选项无法识别/错误的寄存器名称错误)

c - TraceFS : ioctl: inappropriate ioctl for device

c - C有连接运算符吗?

r - 用给定的长度和内容初始化列表

java - 选择一种数据结构来存储句子中的单词及其起始位置

c++ - 打印数据 QTextDocument 和 QPainter

c++ - 与标准库名称冲突

c++ - UnitTest++ 问题 : Trying to use a Predicate that has state

C 代码不起作用,但未显示错误

c# - 在哈希集中实现 FIFO 行为