1 /* kbFile.c 2 This example shows how to save keyboard input to a disk file. 3 System calls used in this program: 4 . write(), read(), open(), close(), exit(). 5 */ 6 #include 7 #include 8 #include 9 #include 10 #define FMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) 11 main() 12 { 13 char buf[BUFSIZ]; 14 char PROMPT1[] = "Please enter output filename >> "; 15 char PROMPT2[] = "Please enter input, to be terminated by \n"; 16 char ERR[] = "Can't open output file\n"; 17 int fd; 18 ssize_t nread; 19 write(STDOUT_FILENO, PROMPT1, strlen(PROMPT1)); /* write to stdout */ 20 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 21 buf[nread-1] = '\0'; /* strip \n & NULL-terminate buf */ 22 if ((fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, FMODE)) == -1) { 23 write(STDERR_FILENO, ERR, strlen(ERR)); /* write to stderr */ 24 return(1); 25 } 26 write(STDOUT_FILENO, PROMPT2, strlen(PROMPT2)); 27 while (1) { 28 nread = read(STDIN_FILENO, buf, BUFSIZ); /* count char's read */ 29 if (nread > 0) 30 write(fd, buf, nread); /* save to file */ 31 else 32 break; /* EOF detected - assume no error */ 33 } 34 close(fd); /* close output file */ 35 exit(0); /* cool */ 36 }