簡體   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