Загрузка данных


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <string.h>

#define BUF_SIZE 4096

static void process_buffer(char *buf, int *len, long long *sum) {
    int start = 0;

    for (int i = 0; i < *len; i++) {
        if (buf[i] == '\n') {
            buf[i] = '\0';
            *sum += atoll(buf + start);
            start = i + 1;
        }
    }

    if (start > 0) {
        memmove(buf, buf + start, *len - start);
        *len -= start;
    }
}

int main(void) {
    int fd1 = open("in1", O_RDONLY);
    int fd2 = open("in2", O_RDONLY);

    if (fd1 < 0 || fd2 < 0) {
        return 1;
    }

    char buf1[BUF_SIZE];
    char buf2[BUF_SIZE];
    int len1 = 0, len2 = 0;

    long long sum = 0;

    int active1 = 1, active2 = 1;

    while (active1 || active2) {
        fd_set rfds;
        FD_ZERO(&rfds);

        int maxfd = -1;

        if (active1) {
            FD_SET(fd1, &rfds);
            if (fd1 > maxfd) maxfd = fd1;
        }

        if (active2) {
            FD_SET(fd2, &rfds);
            if (fd2 > maxfd) maxfd = fd2;
        }

        if (select(maxfd + 1, &rfds, NULL, NULL, NULL) <= 0)
            continue;

        if (active1 && FD_ISSET(fd1, &rfds)) {
            ssize_t n = read(fd1, buf1 + len1, BUF_SIZE - len1 - 1);

            if (n == 0) {
                active1 = 0;
                close(fd1);
            } else if (n > 0) {
                len1 += n;
                buf1[len1] = '\0';
                process_buffer(buf1, &len1, &sum);
            }
        }

        if (active2 && FD_ISSET(fd2, &rfds)) {
            ssize_t n = read(fd2, buf2 + len2, BUF_SIZE - len2 - 1);

            if (n == 0) {
                active2 = 0;
                close(fd2);
            } else if (n > 0) {
                len2 += n;
                buf2[len2] = '\0';
                process_buffer(buf2, &len2, &sum);
            }
        }
    }

    printf("%lld\n", sum);
    return 0;
}