Hey,
Is it even possible to write to a binary file a number as an int and not as a string? If yes how do i write it and how to i read it?
Hey,
Is it even possible to write to a binary file a number as an int and not as a string? If yes how do i write it and how to i read it?
To write an integer to a file
To read an integer from a fileCode:int i; fwrite(&i,sizeof(i),1,f);
(Where 'f' is a file pointer)Code:int i; fread(&i,sizeof(i),1,f);
You should also check for errors and act on them...
The *nix read and write operate on bytes, so the bytes could be the bytes of the int value in memory, or they could be the bytes of a string representation of the number; it's up to you.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Here is using the "read" and "write" system calls directly.
Note that this program needs no header files, as it is accessing the Linux system calls directly rather than using any library functions
Here's the output:Code:// SYSTEM CALL NUMBERS #define SYSCALL_READ 0 #define SYSCALL_WRITE 1 // STANDARD FILE DESCRIPTORS #define STDIN 0 #define STDOUT 1 long syscall(long number, ...); const char msg[] = "Hello world! Press Enter\n"; int main(void) { char buffer[1]; syscall(SYSCALL_WRITE, STDOUT, &msg, sizeof(msg)-1); syscall(SYSCALL_READ, STDIN, &buffer, 1); return 1; }
Code:$ ./main Hello world! Press Enter $
Or, using the wrapper functions and worrying about endianess:
Code:#include <unistd.h> #include <arpa/inet.h> int n = 1; // Write all bytes of n in BIG ENDIAN format. n = htonl( n ); write( STDOUT_FILENO, &n, sizeof n );