gpt4 book ai didi

c++ - 读写bin文件数据不对

转载 作者:行者123 更新时间:2023-11-28 07:17:42 25 4
gpt4 key购买 nike

我定义了一些复杂的结构并测试了 c++ io 的写入/读取。

但是可能我对io读写的使用不对,所以没有得到我想要的结果,我想可能是我使用的ifstrream read方法不对,希望有人帮忙解决。

LNode结构是这样的:

struct LNode
{
int data;
LNode *next;
};

我用来处理 io 的代码在这里:

LNode *tmp;
tmp = NULL;

LinkList l = L->next;

ofstream myfile_tom("struct.dat", ios::out | ios::binary);

while ( l ){

tmp = l;
cout<<tmp->data<<endl;
myfile_tom.seekp(0);
myfile_tom.write((char*)tmp, sizeof (LNode) );

l = l->next;

}
cout<<"write end\n";


//closing file
myfile_tom.close();

// read and write methods accept a char* pointer

// read code
LNode *y = new LNode[5];

ifstream myfile ("struct.dat", ios::in | ios::binary | ios::ate );
myfile.seekg(0);
myfile.read((char*)y, sizeof(LNode) * 5);


(LNode *)y;

// test if read successful
cout<< "test"<< endl;
cout<<"y[0].data"<<y[0].data<<endl;
cout<<"y[1].data"<<y[1].data<<endl;
cout<<"y[2].data"<<y[2].data<<endl;
cout<<"y[3].data"<<y[3].data<<endl;
cout<<"y[4].data"<<y[4].data<<endl;
//

myfile.close();

其中 L 是一个 LinkList,我已经使用“1, 2, 3, 4,5”对其进行了初始化;

typedef LNode *LinkList;

int p;

int status;
status = InitList( L );

for ( p=1; p <= 5; p++)
status = ListInsert(L, 1, p);

所有需要的背景定义都在这里:

int InitList(LinkList &L)
{
L = (LinkList)malloc(sizeof(struct LNode));
if(!L)
exit(OVERFLOW);
L->next=NULL;
return 1;
}

int ListInsert(LinkList L, int i, int element) {
//
int j = 0;
LinkList p = L, s;

while( p&&j<i-1)
{
p = p->next;
j++;
}

if (!p||j>i-1 )
return 0;

s = (LinkList)malloc(sizeof(LNode));
s->data = element;
s->next = p->next;
p->next = s;
return 1;

}

void visit( int c ) //
{
printf("%d ",c);
}

int ListTraverse( LinkList L , void (*vi)(int)){

LinkList p = L->next;
while ( p ) {
vi(p->data);
p = p->next;
}
printf("\n");
return 1;
}

我的程序的输出是:

after insert at the LinkList L's head insert 1~5:L=
5 4 3 2 1
5
4
3
2
1
write end
test
y[0].data1
y[1].data-842150451
y[2].data-842150451
y[3].data-842150451
y[4].data-842150451

只有 y[0] 是对的,

所以我在消费。

最佳答案

您的代码将整个 LNode 存储到文件中,其中包括 next 指针。但是,指针是动态的东西,代表内存中的当前地址。存储这些没有意义。

如果您只是想存储数据,然后用相同的数据重建一个链表,您的初始写循环应该只写出数据字段而不是 next 指针。稍后,当您读入数据时,您应该分配新的结构并在代码中建立next 指针,并在分配结构后将数据读入其他字段。

综上所述,即使出于“错误的原因”,您的代码似乎仍能正常运行。我怀疑真正的错误是你循环中的这个 seekp,它会导致你一遍又一遍地覆盖文件的前面部分:

myfile_tom.seekp(0);

关于c++ - 读写bin文件数据不对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19968585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com