0

I am trying to write in the cajeros.dat file the values that the user set to the actu variable which is a struct type. I don't get any error but when I check the file, the int values like "cod_cajero" and "den_menor" and "den_mayor" show like some random characters in the file. This is an example:

d El bravo Santiago ¸ýf

"El bravo" and "Santiago" are char values which were inserted correctly but "d" was actually a 100 and "¸ýf" were some other numbers. Can someone help me? I would really appreciate it

int actualizarcajeros();

struct e_cajeros{
    
    int cod_cajero;
    char ubicacion[20];
    char ciudad[20];
    int den_menor;
    int den_mayor;
    
} actu;

int cajeros(){
    int opcion1;
    int consultarcajeros();
    
        while(1){
        printf("Menu Cajeros\n1.Actualizar.\n2.Consultar.\n3.Finalizar\n");
        scanf("%d",&opcion1);
        
        if(opcion1==1){
        
        actualizarcajeros();
        }
        
        
        }
    
}
actualizarcajeros(){
    FILE *fp;
    fp=fopen("cajeros.dat","a");
    printf("ingresa el codigo del cajero");
    scanf("%d",&actu.cod_cajero);
    printf("ingresa la ubicacion del cajero");
    gets(actu.ubicacion);   
    printf("ingresa el ciudad del cajero");
    gets(actu.ciudad);
    printf("ingresa la denominacion menor");
    scanf("%d",&actu.den_menor);
    printf("ingresa la denominacion menor");
    scanf("%d",&actu.den_mayor);
    fwrite(&actu,sizeof(actu),1,fp);
    fclose(fp);
}
Oka
  • 23,367
  • 6
  • 42
  • 53
  • 3
    Please read the [fwrite manual](https://linux.die.net/man/3/fwrite). It writes *binary* data not text data. So you can't expect to see `100` in the file as is it writing 100 binary not 100 text. – kaylum Apr 15 '22 at 11:25
  • Then why the chars are inserted correctly? – Omar Almonte Apr 15 '22 at 11:30
  • Because those binary char values can be represented as text. Also, look in any [ascii table](https://man7.org/linux/man-pages/man7/ascii.7.html). Unsurprisingly you will find that the binary value 100 is text character `'d'`. – kaylum Apr 15 '22 at 11:34
  • 2
    Obligatory: [Why is the `gets` function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/2505965) – Oka Apr 15 '22 at 11:37
  • text files contain characters and can be printed. binary files contain data that must be interpreted by a program. – stark Apr 15 '22 at 11:46
  • Use `sprintf` to print out your integer values as text in a character buffer that you write to your file – mmixLinus Apr 15 '22 at 13:41

0 Answers0