10. File input/output
File as a stream
- teletype
- serial
- tape
- ...
- File IRL: see prev. lection
- Why stream: sequential nature of I/O
C files
C: FILE * abstraction
You may try cc -E program_with_FILE.c, but it's a complex structure
Buffer tricks like ungetc() or scanf() next character preview
- text/binary abstraction
OS files
- Linux: stream file I/O as descriptors
- Descriptor: integer stream number
- All other stuff is hidden by OS
- 0, 1, 2 — stdin, stdout, stderr, already opened
ssize_t read(int fd, void *buf, size_t count);
note ssize_t type
note void *buf
also ssize_t write(int fd, const void *buf, size_t count);
Try to use Tab keys
Press ^D at the beginning of the line to notify OS that stdin is closed (see stty --all eof parameter)
Try to change char to int (and 1 to … what?). Describe the result
int open(const char *pathname, int flags);()
returns first free descriptor, usually 3
- flags: (many, see man)
off_t lseek(int fd, off_t offset, int whence);
- Return value and SEEK_SET/SEEK_CUR/SEEK_END
- Cant' seek on a stream!
Files and filesystems
Filesystem objects:
- files
- directories
- symlinks
- devices
- pipes (aka FIFOs)
sockets (aka i've got a hole in me pocket)
- async!
- …
There's also f- versions of tell/stat/whatever over C file abstraction
== C: using command line arguments =
int main(int argc, char *argv[]):
argc is command line size in words (always ⩾ 1)
argv[0] always present, it's the program name
argv[1] etc. are commandline words
these are four words brcause of quotation: qwe "ads df d" sdfsdf " sdfsd ,kuii iu"
char *argv[] is an array of char *, each pointing to corresponded ASCIIZ data block
argv[k] when k>argc is undefined
H/W
TODO