Search code examples
cstdio

fread fwrite problem with two-dimensional char


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?


Solution

  • 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.