Vitor Costa Vitor Costa - 1 year ago 125
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");

reg buffer;

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

is a
for a

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

Function for writing the file:

void register_new() {


reg buffer;

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

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


fwrite(&buffer, sizeof(reg), 1, 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 Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download