文件操作
底层文件操作(关于文件的系统调用)
close
(1) 用法
man 2 close
终止指定文件描述符与对应文件之间的关联,
并释放该文件描述符,即该文件描述符可被重新使用
(2)返回值
成功: 0
失败: -1
实例:
使用read/write实现文件复制
close_demo.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define FILE1_NAME "file1.txt"
#define FILE2_NAME "file2.txt"
int main(void){
int file1, file2;
char buffer[4096];
int len = 0;
file1 = open(FILE1_NAME, O_RDONLY); //O_RDONLY
if( file1 < 0){
printf("open file %s failed\n, reason: %s\n", FILE1_NAME, strerror(errno));
exit(-1);
}
file2 = open(FILE2_NAME, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR);
if( file2 < 0){
printf("open file %s failed\n, reason: %s\n", FILE2_NAME, strerror(errno));
exit(-1);
}
while( (len=read(file1, buffer, sizeof(buffer))) > 0){
write(file2, buffer, len);
}
close(file2);
close(file1);
return 0;
}
运行结果:
观察耗时
./a.out
time ./a.out
补充:time命令
time命令分别输出:
real - 程序总的执行时间、
usr - 该程序本身所消耗的时间、
sys - 系统调用所消耗的时间
具体:
结语:
时间: 2020-07-30