【问题标题】:Regarding Storing Structure in file using read and write关于使用读写在文件中存储结构
【发布时间】:2012-10-29 07:05:05
【问题描述】:

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

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(它们是直接系统调用 rite)...我无法将其写入我的write函数显示错误,即返回-1...上面的代码有什么问题吗...

【问题讨论】:

  • 如果系统调用(如readwrite)返回-1,则表示有问题。您可以通过查看errno 找出什么 错误。
  • 我收到错误的文件描述符错误...这是什么意思? @JoachimPileborg
  • 请显示您打开文件的方式。
  • fd=open("rohit",O_CREAT,(mode_t)0600);
  • 您尚未打开文件进行写入。尝试添加 O_RDWR。另外,请务必检查函数的所有返回值...

标签: c++ c data-structures struct


【解决方案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;
}

【讨论】:

    【解决方案2】:

    看到你把它标记为 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;
    }
    

    现在要对x 的状态进行跟踪,我们可以执行以下操作

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

    反序列化

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

    【讨论】:

    • 我面临的问题是....没有这样的文件或目录错误...虽然文件在那里... fd=creat("rohit",0666);...fd =open("rohit",O_RDWR);........当我使用 write 系统调用写入时,它显示错误 No such file or directory
    • 现在我指定的代码没有错误......但是虽然写函数返回8..读取函数无法读取并返回0....这是为什么?跨度>
    • 因为您没有在写入和读取之间重置文件指针(写入后它指向文件末尾)。医生推荐lseek。
    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多