0

so I'm trying to read a string back from a binary file that I've created,however, I'm unable to do so, I tried reading the string character by character, as well as a whole but none of these two worked, here's my code

int charge_Index(int Index[],int num)
{
    char name[100];
    nom_fich_Index(num,name);//generates the name of the file
    FILE *f = fopen(name,"rb+");
    int i=0,j=0;
    char num[max_char];
    if(f!=NULL)
    {
        fseek(f,0,SEEK_SET);
        while(!feof(f))
        {
            j = 0;
            strcpy(num,"");
            while(j<10)
            {
                fread(&num[j],sizeof(char),1,f);
                j = j+1; 
            }
            num[11] = '\0';
            Index[i] = atoi(num);
            i = i + 1;
        }
    fclose(f);
    }
    else
    {
        printf("error when opening the file \n");
        exit(1);
    }
    return i;
}

I was also wondering if it is necessary when writing a string in a binary file to add a null terminator?

Sab
  • 11
  • 1
    First, read this: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – WhozCraig Jan 06 '22 at 19:40
  • You also need to check the return value from your IO calls like `fread()`. – Andrew Henle Jan 06 '22 at 19:44
  • thank you for your response , I now know what I need to change ^_^ – Sab Jan 06 '22 at 19:46
  • Fyi, `fread` one octet at a time is dreadful. A `fgetc` or `getc`, solution would be far better, and considerably reduce the code complexity as a bonus if done correctly. Also, `strcpy(num, "");` is insane. `num[0] = 0;` (or `*num = 0;`) accomplishes the desired effect without requiring a library call to do it. Finally, you have id-shadowing in this function. `num` is both an `int` argument *and* a local scope `char[max_char]` var. It shouldn't even compile. – WhozCraig Jan 06 '22 at 19:48
  • You don't need a null terminator in a binary file, if you have another method for storing the size of the string, and also of reading it back into memory keeping that in mind. That is pretty standard for any type of binary format. – Cheatah Jan 06 '22 at 19:59
  • thank you all for your helpful answer , I did rewrite the function and hopefully it does work now :) – Sab Jan 06 '22 at 23:37

0 Answers0