ex-3.6.c (1519B)
1 /* 2 * Advanced Programming in the UNIX(r) Environment 3 * 4 * Exercise 3.6 5 */ 6 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <unistd.h> 10 #include <fcntl.h> 11 #include <sys/types.h> 12 #include <sys/stat.h> 13 14 #define FILE "test" 15 16 int 17 main(void) 18 { 19 int fd; 20 char buf[10] = { 0 }; 21 22 printf("lseek(2) test for RW file with append flag\n\n"); 23 24 /* open the file */ 25 printf("open(2)..."); 26 if( (fd = open(FILE, O_RDWR | O_APPEND | O_CREAT | O_TRUNC, S_IRWXU)) == -1 ) { 27 printf(" KO\n"); 28 return EXIT_FAILURE; 29 } 30 printf("OK\n"); 31 32 /* write something */ 33 printf("write(2)..."); 34 if( write(fd, "{first write call}", 18) != 18 ) { 35 printf(" KO\n"); 36 (void)close(fd); 37 return EXIT_FAILURE; 38 } 39 printf(" OK\n"); 40 41 printf("\nTrying to seek 5 bytes from the beginning of the file..\n\n"); 42 43 /* move somewhere */ 44 printf("lseek(2)..."); 45 if( lseek(fd, 5, SEEK_SET) < 0 ) { 46 printf(" KO\n"); 47 (void)close(fd); 48 return EXIT_FAILURE; 49 } 50 printf(" OK\n"); 51 52 /* read something */ 53 printf("read(2)..."); 54 if( read(fd, buf, 5) == -1 ) { 55 printf(" KO\n"); 56 (void)close(fd); 57 return EXIT_FAILURE; 58 } 59 printf(" OK\n"); 60 61 /* write something, again */ 62 printf("write(2)..."); 63 if( write(fd, "[2nd write]", 11) != 11 ) { 64 printf(" KO\n"); 65 (void)close(fd); 66 return EXIT_FAILURE; 67 } 68 printf(" OK\n"); 69 70 close(fd); 71 72 printf("\nTest finished. Check the '%s' file.\n", FILE); 73 74 return EXIT_SUCCESS; 75 } /* eof main() */ 76