关于mmap
  • 板块学术版
  • 楼主STA_Morlin
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/4/1 11:59
  • 上次更新2024/4/1 15:45:01
查看原帖
关于mmap
347089
STA_Morlin楼主2024/4/1 11:59

请问有没有什么方法能用mmap向stdout输出,我这个只能读写文件QAQ

#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
using namespace std;

#define LOCAL

namespace IO {

#define tpl template<typename T>
#define tpa template<typename T,typename... Args>

    const size_t SIZE = 3333333 * 22;

    #ifdef LOCAL
        int ifd = open("1.in", O_RDONLY), ofd = open("test1.out", O_RDWR | O_CREAT, 0777);
    #else
        int ifd = fileno(stdin), ofd = fileno(stdout);
    #endif
    
    const char *ibuf = (char*) mmap(nullptr, SIZE, PROT_READ, MAP_PRIVATE, ifd, 0);

    tpl inline void read(T &x) {
        x = 0; T f = 1;
        while (!isdigit(*ibuf)) {
            if (*ibuf == '-') f = -1;
            ++ibuf;
        }
        while (isdigit(*ibuf))
            x = x * 10 + *ibuf++ - '0';
        x *= f;
    }
    inline void reads(char *s) {
        while (!isdigit(*ibuf)) ++ibuf;
        int i = 0;
        while (isdigit(*ibuf)) s[i++] = *ibuf++;
        s[i] = '\0';
    }
    tpa inline void read(T& x,Args&... args){read(x);read(args...);}

#define putchar(x) (obuf[bufl++] = x)

    char obuf[SIZE]; int bufl;

    tpl inline void print(T x) {
        static T st[45]; T top = 0;
        if (x < 0) x=-x, putchar('-');
        do { st[top++] = x % 10; } while (x /= 10);
        while (top) putchar(st[--top] + '0');
    }

    tpl inline void print(T x, const char c) { print(x); putchar(c); }

    inline void prints(const char *c) { while (*c) putchar(*c++); putchar('\n'); }

    inline void flush() {
        lseek(ofd, bufl - 1, SEEK_SET);
        write(ofd, " ", 1);
        char *buffer = (char *) mmap(nullptr, bufl, PROT_READ | PROT_WRITE, MAP_SHARED, ofd, 0);
        close(ofd);
        memcpy(buffer, obuf, bufl);
        munmap(buffer, bufl);
    }
} using namespace IO;

signed main() {
    clock_t ST = clock();

    int T = 3333333;
    while (T--) {
        int a, b; read(a, b);
        print(a + b, '\n');
    }
    flush();

    clock_t ED = clock();
    cerr << fixed << setprecision(5) << (double)(ED - ST) / CLOCKS_PER_SEC << endl;
    return 0;
}
2024/4/1 11:59
加载中...