二维字符的 fread fwrite 问题
po = fopen("C:\\Progra~1\\WinLib\\settings.txt","w+");
num=1;
fwrite(&num,sizeof(int),1,po);
char* kra[2]={"asdasdasd","123123123"};
h=sizeof(kra[0]);
fwrite(&h,sizeof(int),1,po);
h=sizeof(kra[1]);
fwrite(&h,sizeof(int),1,po);
fwrite (kra[0] , 1 , sizeof(kra[0]) , po );
fwrite (kra[1] , 1 , sizeof(kra[1]) , po );
rewind(po);
char* c1;
char* c2;
fread(&num,1,sizeof(int),po);
fread(&h,1,sizeof(int),po);
fread(&k,1,sizeof(int),po);
c1=(char*) malloc (sizeof(char)*h);
c2= (char*) malloc (sizeof(char)*k);
fread (c1,1,h,po);
fread (c2,1,k,po);
printf("%s %s\n",c1,c2);
但输出不是 asdasdasd 123123123
而是 asda─ 1231─
我需要更改什么?
po = fopen("C:\\Progra~1\\WinLib\\settings.txt","w+");
num=1;
fwrite(&num,sizeof(int),1,po);
char* kra[2]={"asdasdasd","123123123"};
h=sizeof(kra[0]);
fwrite(&h,sizeof(int),1,po);
h=sizeof(kra[1]);
fwrite(&h,sizeof(int),1,po);
fwrite (kra[0] , 1 , sizeof(kra[0]) , po );
fwrite (kra[1] , 1 , sizeof(kra[1]) , po );
rewind(po);
char* c1;
char* c2;
fread(&num,1,sizeof(int),po);
fread(&h,1,sizeof(int),po);
fread(&k,1,sizeof(int),po);
c1=(char*) malloc (sizeof(char)*h);
c2= (char*) malloc (sizeof(char)*k);
fread (c1,1,h,po);
fread (c2,1,k,po);
printf("%s %s\n",c1,c2);
but the output isn't asdasdasd 123123123
it's asda─ 1231─
What do I need to change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 kra 变量是一个指针数组,然后您将其分配给两个常量字符串。
sizeof() 调用将为您提供指针的大小(假设您使用的是 32 位计算机,因此这是 4 个字节)。您需要使用 strlen( kra[0] ) 将字符串的整个长度写入文件。
Your kra variable is an array of pointers that you are then assigning to two constant strings.
The sizeof() call will give you the size of the pointer (presumably you're on a 32 bit machine, and so this is 4 bytes). You need to use strlen( kra[0] ) to write the whole length of the string to the file.
必须更改为与
kra[1]
相同must be changed to
The same for
kra[1]
使用
strlen
而不是sizeof
,这是一个很好的 总结。Use
strlen
rather thansizeof
, here is a good sumup.