RuD_wow
RuD_wow

Reputation: 1

fwrite() puts unknown zero

I have one strange problem while using fwrite() in C.After editing of file with integers, i get zero ("0") before my last element which added by fwrite().My exercise is to divide integers in file on groups which are consisted of 10 elements or less.

For example, i have : {2, 3, 9, 4, 6, 7, 5, 87, 65,12, 45, 2, 3, 4, 5, 6, 7, 8, 9}

after editing i need : {2, 3, 9, 4, 6, 7, 5, 87, 65, 12, 87, 45, 2, 3, 4, 5, 6, 7, 8, 9, 45 };

With code below I get: {2, 3, 9, 4, 6, 7, 5, 87, 65, 12, 87, 45, 2, 3, 4, 5, 6, 7, 8, 9, 0, 45 }; In the process of step-by-step debugging fwrite() works only two times, it wites 87 after first ten elements, and 45 after remained.Zero wasn`t writed by fwrite().Is that so?From where it comes finally?

My code:

while (!feof(fp)) {

        fread(&elems[k], sizeof(int), 1, fp);
        fwrite(&elems[k], sizeof(int), 1, hp);
        ++k;

        if (k == 10 || feof(fp)){
            for (i = 0; i < 10; ++i){
                if (elems[i] > max_number){
                    max_number = elems[i];
                }
            }
            fwrite(&max_number, sizeof(int), 1, hp);
            for (i = 0; i < 10; ++i){
                elems[i] = 0;
            }
            max_number = INT_MIN;
            k = 0;
        }

    }

Thank for answers!

Upvotes: 0

Views: 421

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54355

  • Using feof will result in reading an extra item.
  • Must check for errors from fwrite and fread calls.
    • One possible error is the EOF error.
    • If fread returns 0 items read the value will be left at whatever it was before. Probably 0. Which is probably where your extra 0 comes from.

Upvotes: 1

Related Questions