-1

I'm having trouble when trying to read an integer from a text file:

#include <stdio.h>
#include <string.h>

int main()
{  
    int op;

    /* Open file for both reading and writing */
    FILE *d = fopen("intento1.txt", "r");
    FILE *f = fopen("bubbletry.txt", "w+");

    /* Read and display data */
    fread(&op, 4, 1, d);

    printf("%d\n", &op);
    fclose(d);
    /* Write data to the file */
    fprintf(f,"%d\n",&op);

    fclose(f);

    return(0);
}

The first number at "intento1.txt" is 30771, but the text written at "bubbletry.txt" is 926363699. Could you tell me why that is happening?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

5

Because you read the first 4 bytes of intento1.txt, '3', '0', '7' '7', into an integer. '3' is 0x33, '0' is 0x30, '7' is 0x37. So you end up reading in 0x33303737, but because you're on a small-endian architecture, the bytes are reversed to 0x37373033, which is the hex representation of 926363699, the ascii representation of which you print to the file with fprintf there.

What you want is to scan the integer in from the ascii representation, either by pulling in the string and converting it or using something like fscanf. Remember that the binary representation of a number is not the same as its ASCII representation.

Taywee
  • 1,313
  • 11
  • 17
3

Usually to read integer or the like, you can use fscanf instead. It's a lot more convenient than fread.

fscanf( fp, "%d", &n );

For an example, check http://www.cplusplus.com/reference/cstdio/fscanf/

artm
  • 17,291
  • 6
  • 38
  • 54
1

In addition to the answer concerning usage of fread(), you haven't passed the intended arguments to your functions correctly. While fread() requires a pointer as argument (pointing to the variable) to read into, both printf() and fprintf() require the value (not the address!) of the formatted argument to be printed. So the same syntax in argument passing works for both functions:

printf("%d\n", op);

fprintf(f,"%d\n", op);

You may also find useful reading these SO posts: fread, reading text files with fread, fprintf.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24