How do I fwrite and fread array of strings to file?

时间:2017-04-10 02:11:57

标签: c arrays io fwrite fread

I want to fwrite an array of strings to a file. Right now, I write first the number of strings in the array, followed by the array using this code:

int rows = 3;
char **c = calloc (rows,sizeof(char*));
c[0] = "cat\0";
c[1] = "dog\0";
c[2] = "mouse\0";

FILE * f = fopen("test", "w");
if (f) {
    fwrite(&rows, sizeof(int), 1, f);
    fwrite(c, sizeof(char*), rows, f);
}
fclose(f);

When I read the data back in, I get an empty char**. Here is my code:

FILE * f = fopen("test", "r");
    if (f) {
        int num = -99;
        fread(&num, sizeof(int), 1, f);
        char** buff = malloc(num*sizeof(char*));
        fread(buff, sizeof(char), num, f);

        buff[num] = 0x00;

        for(int i = 0; i < num; i++) {
            printf("%s ", buff[i]);
        }
        printf("\n");
    }

1 个答案:

答案 0 :(得分:1)

You only write the address of variable c to file 'test' (by function fwrite(c,sizeof...)). Why don't you write the value into the file?