I have a which is launched in repl.it. The problem is that is doesn't properly reads null-terminated string from the file:
x == 228
y == Hell
x == 228
y == @
The last line should be y == Hell. How to fix my code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct A {
int x;
char *y;
};
#define INITIAL_BUFFER_LENGTH 10
char *read_string_from_file(FILE *handle) {
int string_capacity = 10;
char *string = malloc(string_capacity);
int count = 0;
char c;
while ((c = fgetc(handle)) != '\0') {
string[count] = c;
count++;
if (count == string_capacity) {
string_capacity *= 2;
string = realloc(string, string_capacity);
}
}
string[count] = '\0';
return string;
}
int main(void) {
struct A *obj = (struct A *)malloc(sizeof(struct A));
obj->x = 228;
obj->y = "Hell";
printf("x == %i\n", obj->x);
printf("y == %s\n", obj->y);
FILE *file = fopen("f.txt", "w");
fwrite(&obj->x, sizeof(obj->x), 1, file);
fwrite(&obj->y, strlen(obj->y) + 1, 1, file);
fclose(file);
obj->x = 0;
obj->y = NULL;
file = fopen("f.txt", "r");
fread(&obj->x, sizeof(obj->x), 1, file);
obj->y = read_string_from_file(file);
printf("x == %i\n", obj->x); // must be 228
printf("y == %s\n", obj->y); // must be Hell
return 0;
}