文档详情

Linux学习记录--文件IO操作相关系统编程.pdf

发布:2017-07-06约1.01万字共9页下载文档
文本预览下载声明
文件IO操作相关系统编程 这里主要说两套IO操作接口,分别是: POSIX标准 read |write接口,函数定义在#includeunistd.h ISO C标准 fread |fwrite接口,函数定义在#includestdio.h 有书上说POSIX标准与ISO C标准的区别在于文件读写是否带缓冲区,我则不是很认同,因此POSIX标准下的IO操作也是带缓 冲区的,至于这两个标准下的IO性能谁更加好则不一定,因为这和缓冲区的大小,以及用户逻辑有很大关系。 POSIX标准 ssize_t read (int __fd, void *__buf, size_t __nbytes) ssize_t write (int __fd, constvoid *__buf, size_t __n) 读规则: 如预读字节数文件总字节数,则全部读入文件字节数,返回值为文件字节数 如预读字节数文件总字节数,则读满__buf(以__nbytes为准)后返回,下回读取会将继续读 如读到文件末尾,则返回值为0 比如:文件长度是100,buf长度是70,那么第一个读取70,读2此会读取剩下的30 ,第三次由于文件游标已经处于文件末 尾,则返回0 写操作 1 #include unistd.h 2 #include fcntl.h 3 #includestdio.h 4 #define BUFFER_SIZE 200 5 int main() { 6 int fd = -1; 7 if (access(/tmp/iofile, F_OK)) { 8 fd = creat(/tmp/iofile, 0777); 9 } else { 10 fd = open(/tmp/iofile, O_WRONLY | O_APPEND); 11 } 12 if (fd == -1) { 13 perror(文件打开错误!); 14 return -1; 15 } 16 char buf[BUFFER_SIZE]; 17 int val = 0, sum = 0; 18 do { 19 val = read(0, buf, BUFFER_SIZE); 20 if (val 0) { 21 write(fd, buf, BUFFER_SIZE); 22 } else { 23 break; 24 } 25 sum += val; 26 } while (1); 27 printf(写入数据总长度是:%d\n, sum); 28 return 1; 29 } 读操作 1 #include unistd.h 2 #include fcntl.h 3 #includestdio.h 4 #define BUFFER_SIZE 400 5 int main() { 6 int fd = open(/tmp/iofile, O_RDONLY); 7 if (fd == -1) { 8 perror(文件打开错误!); 9 return -1; 10 } 11 char buf[BUFFER_SIZE]; 12 int val = 0, sum = 0; 13 do { 14 val = read(fd, buf, BUFFER_SIZE); 15 printf(读入数据长度是:%d\n, val); 16 if (val 0) { 17 write(1, buf, BUFFER_SIZE); 18 printf(\n); 19 } else { 20 sleep(1); 21 } 22 sum += val; 23 } while (1); 24 return
显示全部
相似文档