2012-10-29 22 views
0

我需要在结构为持久即希望将其存储在一个文件中,需要读取字符的字符的数据文件存储结构......为此,我写了下面的代码...下面的代码是不工作也无法写入结构到文件(逐个字符)...... 我需要一个字符为单位关于使用读写

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的.. 。但我想按字符做这个字符...所以我正在使用读取&写(他们是直接系统调用仪式)...我无法写入它我写功能显示错误我.E它返回-1 ...这有什么错在上面的代码...

+1

如果一个系统调用(LI ke'read'或'write')返回'-1',这意味着有什么错误。通过检查['errno'](http://en.cppreference.com/w/c/error/errno)可以发现_what_错误。 –

+0

我越来越差的文件描述符错误...这是什么意思? @JoachimPileborg – Rohit

+0

请说明你如何打开文件。 – ElPaco

回答

0

这里有,如果你愿意,你可以使用两种功能:

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

Thanx很多.....现在它正在工作... @ElPaco – Rohit

0

看到你这个标记为C++,我给你的C++的答案。

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

struct { 
    int y; 
    char c; 
}; 

而且要连载它的状态,并从磁盘,要做到这一点,我们需要创建一些流插入和流提取opterators;

//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 x1 { 29, 'A' }; 
std::ofstream file("rohit"); 
file << x1; 

和AN x的状态,我们可以做的到deserialise

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

我面临的问题是...没有这样的文件或目录错误...虽然文件存在... fd = creat(“rohit”,0666); ... fd = open(“rohit” ,O_RDWR); ..............当我写入使用写入系统调用它显示错误没有这样的文件或目录 – Rohit

+0

并与我列出的代码?同样的错误? – 111111

+0

没有在我上面提到的代码 – Rohit