80 likes | 233 Views
File input and output. CS101 2012.1. File. A file is a 1d array of bytes on disk Can grow and shrink at the end, like a vector Interpreting the bytes is the business of the program using the file Bytes in a text (or .cpp) file are assumed to be ASCII code
E N D
File input and output CS101 2012.1
File • A file is a 1d array of bytes on disk • Can grow and shrink at the end, like a vector • Interpreting the bytes is the business of the program using the file • Bytes in a text (or .cpp) file are assumed to be ASCII code • Bytes in a.out are assumed to be compiled executable code • The hexdump utility to view bytes in a file Chakrabarti
ofstream #include <fstream> using namespace std; ofstream of(“/path/to/file”); of << 2 << 3 << (2-3) << endl; of.close(); If file does not exist, it is created empty. If it exists, it is truncated to zero bytes. A write cursor is initialized to 0. On Linux, 0x0a (linefeed) appended. On Windows, 0x0d (carriage return), then 0x0a are appended. Write cursor increased by 1 or 2. Integer 3 is translated to string “3”. The ASCII code byte for char `3’ (0x33) is appended to file. Write cursor is incremented. Chakrabarti
ios flags to open fstream • ios::binaryOpen in binary mode (no CRLF patch ups) • ios::atePosition write cursor at end of file (as against beginning by default) • ios::truncTruncate file, similar to vec.resize(0)Create file if it does not exist already • ios::in and ios::outOpen for read, write, both Chakrabarti
fstream: read and write fstream fs(“/path/to/file”, ios::binary | ios::in | ios::out | ios::trunc); char buf[100]; fs.read(buf, 100); // read/get cursor fs.write(buf, 100); // write/put cursor This block will be copied to or from the file (what part of the file?) buf Data blockin RAM 100 bytes Chakrabarti
Get and put cursors px gx • Every read advances gx; every write advances px • No ordering beween gx and px in general • Can also be set using seekg and seekp • And current position known using tellg and tellp • Writing may extend the file • Reading past end sets EOF on fstream Chakrabarti
tellg, tellp, seekg, seekp fstream fs(“/path/to/file”, ios::binary | ios::in | ios::out | ios::trunc); // getting cursor positions pos_type gx = fs.tellg() pos_type px = fs.tellp(); // setting cursor positions fs.seekg(gx); fs.seekp(px); Like integers are used to index arrays and matrices, pos_type is used to index bytes in a file Chakrabarti
A vector on a disk file • Does not take up any heap space • Can be deathly slow class FileVector { public: FileVector(char *fname, int siz); void put(int ix, int val); int get(int ix) const; int size() const; }; Chakrabarti