我爱抄代码1-文件IO
作者:互联网
copy.c来自《linux-Unix系统编程手册》,用来将一个源文件,复制到一个目标文件
#include <sys/stat.h> #include <fcntl.h> #include "tlpi_hdr.h" #ifndef BUF_SIZE /* Allow "cc -D" to override definition */ #define BUF_SIZE 1024 #endif int main(int argc, char *argv[]) { //输入文件描述符、输出文件描述符、打开配置 int inputFd, outputFd, openFlags; mode_t filePerms; ssize_t numRead; char buf[BUF_SIZE]; if (argc != 3 || strcmp(argv[1], "--help") == 0) usageErr("%s old-file new-file\n", argv[0]); /* Open input and output files */ //以只读方式打开文件 inputFd = open(argv[1], O_RDONLY); if (inputFd == -1) errExit("opening file %s", argv[1]); openFlags = O_CREAT | O_WRONLY | O_TRUNC; filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* rw-rw-rw- */ //打开目标文件,不存在则创建 outputFd = open(argv[2], openFlags, filePerms); if (outputFd == -1) errExit("opening file %s", argv[2]); /* Transfer data until we encounter end of input or an error */ //通过一个1024字节的缓存把输入复制到输出 while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0) if (write(outputFd, buf, numRead) != numRead) fatal("couldn't write whole buffer"); if (numRead == -1) errExit("read"); if (close(inputFd) == -1) errExit("close input"); if (close(outputFd) == -1) errExit("close output"); exit(EXIT_SUCCESS); }
标签:文件,errExit,代码,argv,inputFd,IO,close,numRead,outputFd 来源: https://www.cnblogs.com/wangbin2188/p/16164379.html