Chris
Chris

Reputation: 8412

Integers not writing to file in C

The following code runs fine, except my output file does not contain the integer 10, but instead the characters ^@^@^@ when I open it up in VIM. If I open it in textedit (on the mac) the file appears to be empty.

Does anybody know where I am going wrong here?

#include <stdio.h>
#include <stdlib.h>

#define MAX_LINE 256
#define MAX_NAME 30

int main() {
   FILE *fp;
   char fname[MAX_NAME] = "test1.dat"; 
   int x =10;
   int num= 0;

   if( (fp =fopen(fname, "w")) == NULL) {
      printf("\n fopen failed - could not open file : %s\n", fname);
      exit(EXIT_SUCCESS);
   }

   num= fwrite(&x, sizeof(int), 1, fp);
   printf("\n Total number of bytes written to the file = %d\n", num);

   fclose(fp);

   return(EXIT_SUCCESS);
}

Upvotes: 1

Views: 7826

Answers (5)

NPE
NPE

Reputation: 500167

You're writing binary data and expecting to see ASCII.

You could write the number in ASCII using fprintf: fprintf(fp, "%d", x)

Upvotes: 4

Bruce
Bruce

Reputation: 7132

You're opening your file in binary, so basically, you're writing the ascii character 10, not the number 10. Depending on what you want to do, you can open in text mode, use fprintf...

Upvotes: 0

janneb
janneb

Reputation: 37188

You're writing binary data and expecting ASCII?

If you wish to write formatted data, you can use e.g. the fprintf() function instead of fwrite().

Upvotes: 0

bmargulies
bmargulies

Reputation: 99993

You wrote the binary bytes of the integer to your file, so that's what you've got.

If you want to see a textual '1', use sprintf. Binary files often look empty or strange in text editors.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339776

Your code is writing the binary representation of the four bytes 0x0000000a to the file, i.e. ^@^@^@\n

To write in ASCII, use fprintf instead.

Upvotes: 1

Related Questions