代码示例:unix环境文件IO、出错处理
无干货,纯示例。
#include <fcntl.h>#include <stdio.h>int main(){//先试着打开一个不存在的文件char* filepath = "/home/kent/temp/test-file-io.txt";int fd = open(filepath, O_RDWR);printf("The File Descriptor of an non-existing files is %d \n", fd);if(fd == -1){perror(filepath);}//创建文件fd = open(filepath, O_CREAT|O_RDWR, 0777);printf("The new created File Descriptor is %d \n", fd);//当前偏移量int pos = lseek(fd, 0, SEEK_CUR);printf("On creation, the position is %d \n", pos);//写文件write(fd, "stop-talking-crazy", 12);fsync(fd); //确保内容已写入磁盘pos = lseek(fd, 0, SEEK_CUR);printf("After writing, the position is %d \n", pos);//读文件char buf[100];int n; while((n = read(fd, buf, 10)) > 0){;}printf("The first element of the Buffer after read is %d\n", buf[0]);pos = lseek(fd, 0, SEEK_CUR);printf("After reading, the position is %d \n", pos);//应该从头开始读char new_buf[100];lseek(fd, 0, SEEK_SET);while((n = read(fd, new_buf, 100)) > 0){;}printf("The buffer read as %s \n", new_buf);pos = lseek(fd, 0, SEEK_CUR);printf("After reading from the beginning, the position is %d \n", pos);//关闭文件close(fd);//删除文件remove(filepath); }