日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux-IO之copy的实现

發布時間:2025/3/15 linux 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux-IO之copy的实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 文件描述符
    • 重點函數說明
    • copy的實現

文件描述符

? 所有的I/O操作的系統調用都以文件描述符,一個非負整數(通常是小整數),來指代打開的文件。

重點函數說明

  • open函數打開pathname所標識的文件,并返回文件描述文件描述符
#include <sys/stat.h>#include <fcntl.h>int open(const char *pathname, int flags);int open(const char *pathname, int flags, mode_t mode);int creat(const char *pathname, mode_t mode);int openat(int dirfd, const char *pathname, int flags);int openat(int dirfd, const char *pathname, int flags, mode_t mode);
  • read函數,調用從fd所指代的打開的文件中,讀取至多count字節的數據,并保存到buf中去
#include <unistd.h>ssize_t read(int fd, void *buf, size_t count);
  • write函數,調用從buf中讀取多達count字節數,將數據寫入到fd指代的已打開的文件中
#include <unistd.h>ssize_t write(int fd, const void *buf, size_t count);
  • close函數, 關閉已打開的文件描述符 fd
#include <unistd.h>int close(int fd);

copy的實現

#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位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的linux-IO之copy的实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。