Vitor Costa Vitor Costa - 3 months ago 11
C Question

C - Printing Bin. File In Weird Symbols

I created a function that is successfully reading the binary file but it is not printing as I wanted.

The function:

void print_register() {

FILE *fp;
fp = fopen("data.bin", "rb");

if (fp == NULL) {
error_message("Fail to open data.bin for reading");
exit(0);
}

reg buffer;

while (EOF != feof(fp)) {
fread(&buffer, sizeof(reg), 1, fp);
printf("%s %d %d\n", buffer.name, buffer.age, buffer.id);
}
fclose(fp);
}


Note:
reg
is a
typedef
for a
struct
:

typedef struct registers reg;
struct registers {
char name[30];
int age;
int id;
char end;
};


Function for writing the file:

void register_new() {

system("clear");

reg buffer;

FILE *fp;
fp = fopen("data.bin", "ab");

if (fp == NULL) {
error_message("Error opening file data.bin");
exit(0);
}

write_register(buffer);

fwrite(&buffer, sizeof(reg), 1, fp);

fclose(fp);
}


Posting a printscreen of what was print to be more helpful:

Console Image

As you can see on image, after the "p" (command for printing) is where should be the name, age and id of the struct.

Answer

In register_new(), you have to send the address of buffer in order for write_register() to work properly (right now you're giving it a copy of buffer).

Replace: write_register(buffer); with: write_register(&buffer);

Then correct write_register to take and work with an address instead of a structure.

This might help you understand what's going on: http://fresh2refresh.com/c-programming/c-passing-struct-to-function

Comments