1

I want to get the number of bytes with ftell to read the data form my binary file and ftell returns 108 bytes instead of 144(my binary file actual size)
Here I create the binary file:

void database_add(char *moviestxt_filename, char *database_filename)
{
    FILE *txt = fopen(moviestxt_filename,"r");
    FILE *bin = fopen(database_filename,"wb");
    if(bin == NULL) { printf("Binary file open error\n"); return 0;}`    
    if(txt == NULL) {printf("txt file open error\n"); return 0;}
    movie m; int i=1;
    while(1)
{
        fscanf(txt,"%s",&m.title);
        fscanf(txt,"%d",&m.relese_year);
        fscanf(txt,"%f",&m.imdb_rate);
        fscanf(txt,"%d",&m.duration.hours);
        fscanf(txt,"%d",&m.duration.minutes);
        fseek(bin, 0 , SEEK_END);
        fwrite(&m, sizeof(m), 1, bin); 
        if(feof(txt)) break;
    }
}

Here is the function where I want to read the binary file:

movie* database_read(char *database_filename)
{
    FILE *bin = fopen(database_filename,"rb");
    if(bin == NULL){printf("Binary file open error\n"); return 0;}
    fseek(bin, 0, SEEK_END);
    int size = ftell(bin); //Here I get the wrong size
 // ......
}

here is my main function:

int main()
{
     movie *v;
     database_add("movies.txt","db");
     v = database_read("db");
     return 0;
}
MihaiM
  • 115
  • 4
  • Your reading loop is broken. It's like `while (!feof(txt))`, [which is wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – molbdnilo Dec 14 '18 at 10:33
  • @molbdnilo The database_add function works, I tested it It reads all of the text from movies.txt and this isn't all my code of course it dosen't compile. ( fixed the bug with database_read function, I changed the type to int* ) – MihaiM Dec 14 '18 at 10:40
  • Always check return values of all IO functions (except plain `printf`etc, where you can justifiably just ignore any (output) error). There's no point trying to debug IO code before you do this basic thing. – hyde Dec 14 '18 at 10:44
  • @hyde I checked the binary file and txt file are opened correctly – MihaiM Dec 14 '18 at 10:50
  • And every fscanf and write on every round of the loop? – hyde Dec 14 '18 at 10:53
  • And most importantly, make sure the file close (or flush) succeeds. – hyde Dec 14 '18 at 10:54
  • @hyde The flush was the problem. I added fclose at the end of my database_add function and now the size is correct. Thanks – MihaiM Dec 14 '18 at 11:03

1 Answers1

2

The problem is, you never flush or close your output file. Some data will remain in the buffer.

Also this leaks the file descriptors, which is bad too.

Add to the end of database_add function:

fclose(txt); // read-only file, ignore close error
if (fclose(bin) == -1) {
    perror("closing output file");
    // exit program or return error code or something
}
hyde
  • 60,639
  • 21
  • 115
  • 176