从二进制文件中读取char *结构

时间:2018-04-04 13:51:43

标签: c

我正在尝试从二进制文件中保存并读取struct,我遇到了问题。事情是它似乎正在得到妥善保存。然而,在阅读它时,它要么显示奇怪的字符,要么抛出“分段错误”错误。

这是我的结构:

typedef struct
{
    char* P;
    char* R1;
    char* R2;
    char* R3;
} t_p_r;

这些是我用来读写它们的方法:

保存/读取奇异结构的方法:

void saveSing(t_p_r P)
{
  FILE* f = fopen("PR.dat", "wb"); 
  fputc(1, fichero);
  fwrite(&P, sizeof(t_p_r), 1, f);
  fclose(f);
}

void ReadSing(t_p_r* P)
{
  FILE* f = fopen("PR.dat", "rb");
  fread(P, sizeof(t_p_r) , 1, f);
  fclose(f);
}

方法我试图保存t_p_r

的数组
void SaveR(t_p_r P[], int num)
{
  FILE* f= fopen("PR.dat", "wb");  
  fputc(num, f);
  fwrite(&P, sizeof( t_p_r), num, f);
  fclose(f);
}

int ReadR(t_p_r* P)
{
  int numElem;
  FILE* f= fopen("PR.dat", "rb");
  numElem = fgetc(f);
  P= (t_p_r*) malloc((numElem) * sizeof(t_p_r));
  fread(&P, sizeof(t_p_r) , numElem, f);
  fclose(f);
  return numElem;
}

在第一组方法的情况下,我遇到了稀有符号的问题(不是在char*中输入的那些被保存的符号。在第二组中,我得到A分段错误在试图阅读时。

2 个答案:

答案 0 :(得分:2)

将程序状态保存到文件时,保存指针的值永远不会有意义。从程序调用到程序调用,指针的值永远不会一致。

您必须做的是保存实际数据值。在许多情况下,仅保存数据值是不够的。您可能还需要某种元数据来解释接下来会发生什么。元数据的示例是“类型”(即,下一个字节是int32或int16或字符串)和“字节数”(即下一个变量占用多少字节)。这通常被称为序列化。

您可以找到几乎任何类型的数据类型都具有此类功能的库。

如果您想自己编写,您需要弄清楚要写入文件的内容以及在阅读时如何识别字段。

让我们说你想要的只是保存你的rype t_p_r的对象。要回答的第一个问题是“指向哪些char指针”和“在读取文件时如何识别值”。

让我们说他们指向C型字符串。然后你的方法可能是将每个变量保存在一个新行上。也就是说 - 每个t_p_r将在文件中占用4行。

因此在伪代码中你的写函数将是:

for each t_p_r variable:
    write to file the string that P points and a newline
    write to file the string that R1 points and a newline
    write to file the string that R2 points and a newline
    write to file the string that R3 points and a newline

阅读有点复杂:

while not end of file:
    allocate memory for a t_p_r variable

    read a line from the file
    t_p_r->P = allocate memory to hold the line
    strcpy(t_p_r->P, line)

    read a line from the file
    t_p_r->R1 = allocate memory to hold the line
    strcpy(t_p_r->R1, line)

    read a line from the file
    t_p_r->R2 = allocate memory to hold the line
    strcpy(t_p_r->R2, line)

    read a line from the file
    t_p_r->R3 = allocate memory to hold the line
    strcpy(t_p_r->R3, line)

答案 1 :(得分:1)

您需要将实际字符串写入文件

fputc(strlen(P->P),  f); fwrite(P->P,  strlen(P->P),  1, f);
fputc(strlen(P->R1), f); fwrite(P->R1, strlen(P->R1), 1, f);
fputc(strlen(P->R2), f); fwrite(P->R2, strlen(P->R2), 1, f);
fputc(strlen(P->R3), f); fwrite(P->R3, strlen(P->R3), 1, f);

可能有更好的方法来处理它,但如果没有更多代码,我就无法发表评论。