2013-10-09 112 views
0

我有以下四种结构在我的计划阅读结构对象无效*指针

struct SType{ 
    int type;//struct type 
}; 

struct S1{ 
}; 

struct S2{ 
}; 

struct S3{ 
}; 

我使用下面的代码保存这些结构的状态在一个文件中:

空隙存储(S型结构S1,空隙* S){

//open file and stuff 
//s points to either one of the last three structs 
fwrite(&s1,sizeof(s1),1,file); fwrite(s, size, 1, file); 
//structs are always saved in the file in pairs of SType and either one of the last three structs 
} 

现在当我试图从文件中使用下面的代码检索对的第二个结构时,我得到分段错误。那么,如何使用fread()来检索任意结构类型的对象呢?

void read(){ 
void *record; 
//read struct SType object from the file 
//now read the second struct of the pair 
fread(record,size,1,file); 
} 
+0

我们需要更多的代码。我*猜测*是你没有分配内存来读取'struct'。尽量减少你的代码以免“垃圾”给每个人,但是一个错误代码的小实例将是完美的(而不是伪代码) – noelicus

+0

@noelicus我想读取结构或者将其引用为void *指针....当我读结构时,结构对象read可以是s1,s2或s3的一种类型....稍后在我的代码中,我将把void *指针转换为适当的结构类型指针。 – thunderbird

+0

我的观点是你已经将'read' *写入有效的记忆*,并且我猜测你可能没有那样做。我不得不猜测,因为你没有包括代码,这是我的另一点! – noelicus

回答

2

您必须读入有效内存。 void表示“我不知道”,系统不能也不会为您猜出这个值! 你有什么是:

void read(){ 
void *record;// This pointer currently is a random value - this will cause a fault when you try and copy data into it by calling: 
fread(record,size,1,file); 
} 

它应该是:

void read(){ 
void *record; 
len = ?; // Your program needs to know this. You must know which structure it is somehow if you are to cast it later. Therefore you should know its size. 
record = malloc(len); // Where len has been previously found to be AT LEAST big enough to read into 
fread(record,size,1,file); 
} 

至于你说你的代码是不是伪代码,然后也把东西在你的结构所以他们不为空。一旦你阅读了结构,对结构做些什么也是可取的,例如从你的fread中返回void *。

希望有所帮助。

+0

thx它的工作...'void * pointer = malloc(sizeof(void))'读取整个文件,而不管'fread(pointer,size,1,file)'函数中提供的'要读取的大小'。是的,我没有提供实际的代码..我只是提供了用于读写的实际语法我认为这就够了 – thunderbird

1

你读了一个记录到未初始化的指针,我想你应该先分配内存。

void *record = maloc(size) 

而且不要忘记释放...

我建议你使用一个联盟?

你的类型定义看起来就像这样:

struct SType{ 
    int type;//struct type 
}; 
struct S1{ 
}; 

struct S2{ 
}; 

struct S3{ 
}; 

union S{ 
    S1 s1; 
    S2 s2; 
    S3 s3; 
}; 

现在读写可以做这样的:

SType stype; 
S s; 

fread(&stype,sizeof(stype),1,file); 
size = ??? //get according to type 
fread(&s,size,1,file); 
// your data will be stored according to type in s.s1, s.s2 or s.s3 

size = ??? //get according to type 
fwrite(&stype,sizeof(stype),1,file); 
fwrite(&s,size,1,file); 

下一个阶段,与其他统一类型:

struct S{ 
    int type;//struct type 
    union { 
     S1 s1; 
     S2 s2; 
     S3 s3; 
    }s; 
}; 
/* in case you don't care about loosing file space, 
    you can read\write all in a single operation like this: 
*/ 
S s; 
fread(&s,sizeof(s),1,file); 
// now according to the type you take s.s.s1, s.s.s2 or s.s.s3. 
fwrite(&s,sizeof(s),1,file); 

/* if you do care about loosing file space, you work like before */ 
S s; 
fread(&s.type,sizeof(int),1,file); 
size = ??? //get according to type 
fread(&s.s,size,1,file); 
// as before, you take s.s.s1, s.s.s2 or s.s.s3. 
size = ??? //get according to type 
fwrite(&s.type,sizeof(int),1,file); 
fwrite(&s.s,size,1,file);