0

I have a little program for testing in which I simply fill an array with some shorts. Then I write this array in a File. And then I print the File.

The code is like this:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFERLENGTH 10

short bufo[BUFFERLENGTH];


int main(int argc, char **argv){    

FILE * ff;
bufo [0]= 1;
bufo [1]= 2;
bufo [2]= 3;
bufo [3]= 4;
bufo [4]= 5;
bufo [5]= 6;
bufo [6]= 7;
bufo [7]= 8;
bufo [8]= 9;
bufo [9]= 10;
short s;
printf("Ho \n");

if ((ff = fopen("prueba1", "ab+")) == NULL){
            perror("Abriendo mal"); 
        }
        fwrite(bufo, sizeof(short) , 10, ff);
        fclose(ff);
        printf("FRONTERA \n");

if ((ff = fopen("prueba1", "ab+")) == NULL){
            perror("Abriendo mal"); 
        }
        while(!feof(ff)){
         fread(&s,sizeof(short), 1, ff);
         printf("%u \n",s);

        }

} 

After this I would like to see this output:

1
2
3
4
5
6
7
8
9
10

But instead, I get this :

1
2
3
4
5
6
7
8
9
10
10

Why do I get the last element twice?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Asdemuertes
  • 313
  • 3
  • 6
  • 19
  • Check the result of your fread, feof will only be set if you read the end of the file. More info: https://linux.die.net/man/3/fread – Fernando Coelho Nov 24 '16 at 17:31
  • Not directly related to your question: 1. your code is poorly indented and therefore difficult to read. 2. if `fopen` fails you should not continue after printing "Abriendo mal". – Jabberwocky Nov 24 '16 at 17:33

0 Answers0