页次: 1
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> int main () { char *s = "123456789"; int fd; off_t currpos; char c; fd = creat("new.txt", 0644); if(fd == - 1) { perror("error"); _exit(1); } // 写如数据 if(write(fd, s, strlen(s)) == -1) { perror("write fail"); _exit(2); } close(fd); fd = open("new.txt", O_RDWR | O_APPEND); if(fd == -1) { perror("error"); _exit(1); } else { currpos = lseek(fd, 0, SEEK_SET); printf("this offset if is %d \n", currpos); currpos = lseek(fd, 0, SEEK_END); printf("this offset if is %d \n", currpos); } close(fd); // 文件的读取 fd = open("new.txt", O_RDONLY); while(1) { // 使用一个静态变量,防止无限循环 static int count = 0; // 这里一次只读一个字符 if(read(fd, &c, 1) != 0) { putchar(c); } else { break; } // lseek(fd, 0, SEEK_SET); // 如果有这一行只能打印第一个字符,因为移动文件的指针 // lseek(fd, 0, SEEK_CUR); // 这一行没有什么用 // lseek (fd , 0, SEEK_END);// 如果有了这一行, 仅仅输出一个1, 就结束了。 文件的内部的指针移动到最后了。 count++; if(count > 100) break; } close(fd); return 0; }
ipbbs.net
离线
页次: 1