N
N
natashka422014-05-21 17:58:58
C++ / C#
natashka42, 2014-05-21 17:58:58

Good day. Could you help me understand the function?

This is a file copy function from Linux OS. If possible, the maximum number of comments.

#include <sys/stat.h>
#include <fcntl.h>
#include "tlpi_hdr.h"

#ifndef BUF_SIZE        /* Allow "cc -D" to override definition(разрешает "cc -D"в терминале переопределять описание) */
#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 */

    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);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2014-05-21
@jcmvbkbc

Function as function, nothing remarkable. All calls inside are standard, no tricky flags. There is error handling, but not very diligent.
You can maximize the number of helpful comments by asking specific questions.

D
Dmitry, 2014-05-21
@dmtrrr

It's a file copy function written in C, not C++.

N
natashka42, 2014-05-21
@natashka42

I apologize for the inaccuracy...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question