And this service is provided by the Operating System
One of the resources is disk space and it is part of the job of an Operating System to provide ways for the programmer to read and write bytes (raw data) from and to disk (files)
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int fd; // file identifier fd = open("filename", O_RDONLY); better: if ( (fd = open("filename", O_RDONLY) ) == -1 ) { cout << "Error: can't open file" << endl; exit(1); } |
#include <unistd.h> int n; n = read(fd, MemoryAddress, NBytes) |
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int fd; fd = open("filename", O_WRONLY|O_CREAT|O_TRUNC, 0644); // Overwrites file fd = open("filename", O_WRONLY|O_CREAT|O_APPEND, 0644); // Appends to file better: if ( (fd = open("filename", MODE) ) == -1 ) { cout << "Error: can't create file" << endl; exit(1); } |
Use the O_TRUNC mode if you want to truncate an existing file and overwrite it with new data.
Use the O_APPEND mode if you want to append data to an existing file.
There is also a O_RDWR mode that is used in database application where existing data is updated (read and write permitted) - I don't think numerical analysts will ever use this mode and omit it from the discussion...
Using 0644 will create a file that is Read/Write for owner, and Read Only for everyone else...
#include <unistd.h> close(fd); |
write(fd, MemoryAddress, NBytes); |
#include <sys/types.h> #include <unistd.h> int offset; offset = lseek(int fildes, off_t offset, int whence); |
SEEK_SET |
The new position is equal to offset bytes from the beginning of the file |
SEEK_CUR |
The new position is equal to offset bytes from the current read position in the file |
SEEK_END |
The new position is equal to offset bytes from the end of the file |
Binary outputs are not useful to save data that is intended for human consumption --- unless your hobby is decoding binary representation
The first program uses the binary file "matrix" to transfer information to another program...
Do an octal dump on the file with "od -x matrix" and you will see the binary representation of the integers.