/* off_t lseek(int fd, off_t offset, int whence); *参数 whence SEEK_SET 头 SEEK_CUR 当前位置 SEEK_END 尾 *参数 offset 偏移量(矢量,可以是正值也可以是负值,负值向前偏移) 参数offset 和whence 的含义和fseek 函数完全相同。只不过第一个参数换成 了文件描述符。和fseek 一样,偏移量允许超过文件末尾,这种情况下对该文 件的下一次写操作将延长文件,中间空洞的部分读出来都是0。 若lseek 成功执行,则返回新的偏移量,因此可用以下方法确定一个打开文件 的当前偏移量: off_t currpos; currpos = lseek(fd, 0, SEEK_CUR); 这种方法也可用来确定文件或设备是否可以设置偏移量,常规文件都可以设置 偏移量,而设备一般是不可以设置偏移量的。如果设备不支持lseek,则lseek 返回-1,并将errno 设置为ESPIPE。注意fseek 和lseek 在返回值上有细微的 差别,fseek 成功时返回0 失败时返回-1,要返回当前偏移量需调用ftell,而 lseek 成功时返回当前偏移量,失败时返回-1。 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> int main(void) { int fd, n; char msg[] = "It's a test for lseek\n"; char ch; fd = open("lseek.txt", O_RDWR|O_CREAT|O_TRUNC, 0644); if(fd < 0){ perror("open lseek.txt error"); exit(1); } write(fd, msg, strlen(msg)); lseek(fd, 5, SEEK_SET); //偏移5,从It's a test for lseek的a开始打印 // lseek(fd, 0, SEEK_SET); //偏移0,从It's a test for lseek的I开始打印 while((n = read(fd, &ch, 1))){ if(n < 0){ perror("read error"); exit(1); } write(STDOUT_FILENO, &ch, n); //sleep(1); //putchar(ch); //printf("%c", ch); } close(fd); return 0; } /*akaedu@akaedu-G41MT-D3:~/T74_system/0819_chp1_lseek_ctl_mmap_dup2$ ./lseek a test for lseek */<pre name="code" class="cpp"> //dup dup2 /* *STDIN_FILENO 0 *STDOUT_FILENO 1 *STDERR_FILENO 2 */ #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdio.h> int main(void) { int fd, save_fd; char msg[] = "It's just a test for dup2!\n"; fd = open("test", O_RDWR|O_CREAT|O_TRUNC, 0644); //<fcntl.h> printf("fd = %d\n", fd); if(fd < 0){ perror("open error"); exit(1); } save_fd = dup(STDOUT_FILENO); //STDOUT_FILENO <unistd.h> printf("save_fd = %d\n", save_fd); #if 1 dup2(STDOUT_FILENO, fd); write(fd, msg, strlen(msg)); //fd存的是STDOUT_FILENO,标准输出 #else dup2(fd, STDOUT_FILENO); //STDOUT_FILENO的值为fd,所以无法打印到屏幕 puts(msg); #endif close(fd); return 0; }
//read /* ssize_t read(int fd, void *buf, size_t count); read 到文件尾返回0,出错 -1, 成功返回读到的字节个数(可能小于count,如:read (fd, buf, 10) ,buf大小为[5], 所以返回值为5) */ #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define MSG_TRY "try again\n" int main(void) { char buf[10]; int fd, n; fd = open("/dev/tty", O_RDONLY|O_NONBLOCK); //使用O_NONBLOCK标志设置非阻塞读终端 if(fd < 0){ perror("open /dev/tty"); exit(1); } tryagain: n = read(fd, buf, 10); if(n < 0){ //由于open制定了O_NONBLOCK标志,read读设备,没有数据到达返回-1,同时将error设置为EAGAIN或EWOULDBLOCK if(errno != EAGAIN){ //也可以是 if(error != EWOULDBLOCK)两个宏值相同 perror("read /dev/tty"); exit(1); } sleep(3); write(STDOUT_FILENO, MSG_TRY, strlen(MSG_TRY)); goto tryagain; } write(STDOUT_FILENO, buf, n); close(fd); return 0; } /* akaedu@akaedu-G41MT-D3:~/T74_system/0819_chp1_lseek_ctl_mmap_dup2$ ./1.3 try again try again try again adadwa try again adadwa */