lseek函数(九)
代码:
1 /* 2 标准C库的函数 3 #include <stdio.h> 4 int fseek(FILE *stream, long offset, int whence); 5 6 Linux系统函数 7 #include <sys/types.h> 8 #include <unistd.h> 9 off_t lseek(int fd, off_t offset, int whence); 10 参数: 11 - fd:文件描述符,通过open得到的,通过这个fd操作某个文件 12 - offset:偏移量 13 - whence: 14 SEEK_SET 15 设置文件指针的偏移量 16 SEEK_CUR 17 设置偏移量:当前位置 + 第二个参数offset的值 18 SEEK_END 19 设置偏移量:文件大小 + 第二个参数offset的值 20 返回值:返回文件指针的位置 21 22 23 作用: 24 1.移动文件指针到文件头 25 lseek(fd, 0, SEEK_SET); 26 27 2.获取当前文件指针的位置 28 lseek(fd, 0, SEEK_CUR); 29 30 3.获取文件长度 31 lseek(fd, 0, SEEK_END); 32 33 4.拓展文件的长度,当前文件10b, 110b, 增加了100个字节 34 lseek(fd, 100, SEEK_END) 35 注意:需要写一次数据 36 37 */ 38 39 #include <sys/types.h> 40 #include <sys/stat.h> 41 #include <fcntl.h> 42 #include <unistd.h> 43 #include <stdio.h> 44 45 int main() { 46 47 int fd = open("hello.txt", O_RDWR); 48 49 if(fd == -1) { 50 perror("open"); 51 return -1; 52 } 53 54 // 扩展文件的长度 55 int ret = lseek(fd, 100, SEEK_END); 56 if(ret == -1) { 57 perror("lseek"); 58 return -1; 59 } 60 61 // 写入一个空数据 62 write(fd, " ", 1); 63 64 // 关闭文件 65 close(fd); 66 67 return 0; 68 }