linuxプログラミング-open関数とwrite関数によるcopyコマンドの実装
文書ディレクトリ
ファイル記述子
すべてのI/Oオペレーションのシステム呼び出しは、開いているファイルを指すファイル記述子であり、非負の整数(通常は小さな整数)である.
#include
#include
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);
#include
ssize_t read(int fd, void *buf, size_t count);
#include
ssize_t write(int fd, const void *buf, size_t count);
#include
int close(int fd);
#include
#include
#include
#include
#include
#include
#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)
printf("%s old-file new-file
", 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);
}
完全なコードは次のとおりです.
#include
#include
#include
#include
#include
#include
#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)
printf("%s old-file new-file
", argv[0]);
//<
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);
}
完全版の工事を要してここでgithub住所