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