80 likes | 167 Views
Standard I/O. FILE * stdin: standard input (read-only) FILE * stdout: standard output (write-only) FILE * stderr: standard error output (write-only) File descriptor: stdin: 0 stdout: 1 Stderr: 2. Standard I/O Example. #include <stdio.h> int main() { char buf[1024];
E N D
Standard I/O • FILE * stdin: standard input (read-only) • FILE * stdout: standard output (write-only) • FILE * stderr: standard error output (write-only) • File descriptor: • stdin: 0 • stdout: 1 • Stderr: 2
Standard I/O Example #include <stdio.h> int main() { char buf[1024]; int offset, read_num=0, write_num=0; read_num = read(0, buf, sizeof(buf)); while(read_num > 0){ offset = 0; do { write_num = write(1, buf+offset, read_num); //write_num = fwrite(buf, 1, read_num, stdout); read_num -= write_num; offset += write_num; } while(read_num > 0); read_num = read(0, buf, sizeof(buf)); } return 0; } • read(): return # of bytes read, 0 indicates end of file • write(): return # of bytes write • fwrite(): calls write()
Shell Redirection • Replace stdin/stdout/stderr by another file • Usage: • ./a.out < input.txt • ./a.out > output.txt • ./a.out < input.txt > output.txt • Question: how to achieve this?
Redirect Standard Input (I) #include <stdio.h> int main() { char buf[1024]; int offset, read_num=0, write_num=0; close(0); open(“input.txt", O_RDONLY); read_num = read(0, buf, sizeof(buf)); while(read_num > 0){ offset = 0; do { write_num = write(1, buf+offset, read_num); read_num -= write_num; offset += write_num; } while(read_num > 0); read_num = read(0, buf, sizeof(buf)); } return 0; }
Redirect Standard Input (II) #include <stdio.h> int main() { char buf[1024]; int offset, read_num=0, write_num=0; int input_fd = open("tmp.txt", O_RDONLY); dup2(input_fd, 0); read_num = read(0, buf, sizeof(buf)); while(read_num > 0){ offset = 0; do { write_num = write(1, buf+offset, read_num); read_num -= write_num; offset += write_num; } while(read_num > 0); read_num = read(0, buf, sizeof(buf)); } return 0; }
Redirect Standard Output #include <stdio.h> int main() { char buf[1024]; int offset, read_num=0, write_num=0; int input_fd = open("tmp.txt", O_RDONLY); dup2(input_fd, 0); read_num = read(0, buf, sizeof(buf)); close(1); open("temp.txt", O_WRONLY | O_TRUNC | O_CREAT,0666); while(read_num > 0){ offset = 0; do { write_num = write(1, buf+offset, read_num); read_num -= write_num; offset += write_num; } while(read_num > 0); read_num = read(0, buf, sizeof(buf)); } return 0; }
File Access • Three access levels: • User, Group, Other • For each level, read/write/execute represented by a bit • Example: ls -l shellp.C -rw-r----- 1 bing cse_fac 12187 Sep 20 13:39 shellp.C
Pipes • Unidirectional flow: • Write on source end • Read from sink end • Example: • System call: int pipe(int * filedes) • Hints: • use multiple-processes, wait() cat words.txt | sort | uniq | cat > uniq-sorted-words.txt