Writing an int to a file.

pergolesi

Registered
I'm trying to make an small c application, and one of the features is to write an int to a file, but it doesn't work. I can write anything else, using write and fwrite, like strings and chars, but when I'm trying to write an integer the program only writes empty spaces in the file.
 
Both. When I'm writing to write a binary value a bus error occure, and when trying to write a text representation there is only blank fields.
Insanity. Is there anybody who have experienced this kind problem?
 
Here's a simple C program which writes an integer (somevalue) to a file (file.out):

Code:
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>


int main( void )
{
   int somevalue = 704;
   int file;

   file = open( "file.out", O_CREAT | O_RDWR, 0644 );
   if( file >= 0 )
   {
      write( file, &somevalue, sizeof( somevalue ) );
      close( file );
   }

   return 0;
}

To verify, run hexdump:
Code:
nabu:/Users/blb/src $ hexdump -d file.out 
0000000   00000   00704                                                
0000004
 
I compiled the code and executed the program. In the terminal the hexdump looks just like yours
0000000 00000 00704 0000004
but in finder the hexdump looks like this
00000000 00 00 02 c0 ....

and in the file, which is most important, it only writes "
 
The original hexdump I did had the '-d' switch which causes it to show in decimal; if you run hexdump without, it will print out 2c0 which is simply the hex (base 16) version of 704.
As for the last thing you say, how exactly are you looking at it? When writing in binary (as write was doing) it doesn't write a literal 704 to the file, it writes the number in true binary form instead of text.
 
I am stupid. But how do you write plain text.

&int = writing in binary? What is the syntax to write a plain number?
 
If you mean you want it to appear as (in my example) 704 when looking at it in a text editor, then you need to convert it to a string. Easiest is to use fopen instead of open, then use fprintf:

fprintf( myfile, "%d", somevalue );

Otherwise, use sprintf to convert to a string and write() that.
 
Back
Top