linux-IO之copy的实现
生活随笔
收集整理的這篇文章主要介紹了
linux-IO之copy的实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 文件描述符
- 重點函數(shù)說明
- copy的實現(xiàn)
文件描述符
? 所有的I/O操作的系統(tǒng)調(diào)用都以文件描述符,一個非負(fù)整數(shù)(通常是小整數(shù)),來指代打開的文件。
重點函數(shù)說明
- open函數(shù)打開pathname所標(biāo)識的文件,并返回文件描述文件描述符
- read函數(shù),調(diào)用從fd所指代的打開的文件中,讀取至多count字節(jié)的數(shù)據(jù),并保存到buf中去
- write函數(shù),調(diào)用從buf中讀取多達(dá)count字節(jié)數(shù),將數(shù)據(jù)寫入到fd指代的已打開的文件中
- close函數(shù), 關(guān)閉已打開的文件描述符 fd
copy的實現(xiàn)
#include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h>#ifndef BUF_SIZE /* Allow "cc -D" to override definition */ #define BUF_SIZE 1024 #endifint 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)printf("%s old-file new-file\n", argv[0]);/* Open input and output files */inputFd = open(argv[1], O_RDONLY);if (inputFd == -1)printf("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)printf("opening file %s", argv[2]);/* Transfer data until we encounter end of input or an error */while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0)if (write(outputFd, buf, numRead) != numRead)printf("couldn't write whole buffer");if (numRead == -1)printf("read");if (close(inputFd) == -1)printf("close input");if (close(outputFd) == -1)printf("close output");exit(EXIT_SUCCESS); } 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的linux-IO之copy的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:石勇(1956-),男,中国科学院
- 下一篇: 任女尔(1990-),女,北京卡达克数据