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 #include 11 #include 12 #define FMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) 13 main() 14 { 15 char buf[BUFSIZ]; 16 char PROMPT1[] = "Please enter output filename >> "; 17 char PROMPT2[] = "Please enter input, to be terminated by \n"; 18 char ERR[] = "Can't open output file\n"; 19 int fd; 20 ssize_t nread; 21 write(STDOUT_FILENO, PROMPT1, strlen(PROMPT1)); /* write to stdout */ 22 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 23 buf[nread-1] = '\0'; /* strip \n & NULL-terminate buf */ 24 if ((fd = open(buf, O_WRONLY | O_CREAT | O_TRUNC, FMODE)) == -1) { 25 write(STDERR_FILENO, ERR, strlen(ERR)); /* write to stderr */ 26 return(1); 27 } 28 write(STDOUT_FILENO, PROMPT2, strlen(PROMPT2)); 29 while (1) { 30 nread = read(STDIN_FILENO, buf, BUFSIZ); /* count char's read */ 31 if (nread > 0) 32 write(fd, buf, nread); /* save to file */ 33 else 34 break; /* EOF detected - assume no error */ 35 } 36 close(fd); /* close output file */ 37 exit(0); /* cool */ 38 }