LEC10 Io
LEC10 Io
System-Level I/O
Unix I/O
Standard I/O
Closing remarks
unistd.h
Kernel maintains current working directory (cwd) for each process
Modified using the cd command
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 8
Pathnames
Locations of files in the hierarchy denoted by pathnames
Absolute pathname starts with ‘/’ and denotes path from root
/home/droh/hello.c
Relative pathname denotes path from current working directory
../droh/hello.c
/ cwd: /home/bryant
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition unistd.h 9
Opening Files
When you open a file
Informs the kernel that you are ready to access that
file
int fd; /* file descriptor */
Unix I/O
Standard I/O
Closing remarks
...
...
File B (disk)
File access
File size
File pos
refcnt=1
File type
...
...
...
...
File B (disk)
File pos
refcnt=1
...
...
...
File B (disk)
File access
File size
File pos
refcnt=1
File type
...
...
...
...
...
...
fd 4
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 20
I/O Redirection
Question: How does a shell implement I/O redirection?
linux> ls > foo.txt
...
...
File B
File access
File size
File pos
refcnt=1
File type
...
...
...
...
File B
File access
File size
File pos
refcnt=2
File type
...
...
Unix I/O
Standard I/O
Closing remarks
#include <stdio.h>
extern FILE *stdin; /* standard input (descriptor 0) */
extern FILE *stdout; /* standard output (descriptor 1) */
extern FILE *stderr; /* standard error (descriptor 2) */
int main() {
fprintf(stdout, "Hello, world\n");
}
Bryant and O’Hallaron, Computer Systems: A Programmer’s Perspective, Third Edition 26
Buffered I/O: Motivation
Applications often read/write one character at a time
getc, putc, ungetc
gets, fgets
Read line of text one character at a time, stopping at newline
Implementing as Unix I/O calls expensive
read and write require Unix kernel calls
> 10,000 clock cycles
Solution: Buffered read
Use Unix read to grab block of bytes
User input functions take one byte at a time from buffer
Refill buffer when empty
h e l l o \n . .
fflush(stdout);
Unix I/O
Standard I/O
Closing remarks
fopen fdopen
fread fwrite
fscanf fprintf
sscanf C application program
sprintf fgets
fputs fflush
fseek Standard I/O
fclose functions
open read
Unix I/O functions
write lseek
(accessed via system calls)
stat close
Cons
Efficient reading of text lines requires some form of
buffering, also tricky and error prone
These issues are addressed by the standard I/O package
Cons:
Provides no function for accessing file metadata
Standard I/O functions are not async-signal-safe, and not
appropriate for signal handlers
Standard I/O is not appropriate for input and output on
network sockets
String functions
strlen, strcpy, strcat
Interprets byte value 0 (end of string) as special