在C中实现最快的fgets

Phi*_*lip -2 c performance implementation libc fgets

已知的fgets libc函数实现fgetc()在里面使用,如何使用read()更大的缓冲区或其他方法代替加速函数?

例如,我读取/proc/pid/maps文件来搜索一些字符串.该文件的格式是已知的,目前我使用fgets链接中的实现read(fd, &c, 1);代替getc.我认为从文件读取单字节比读取200字节慢.所以我想修改函数从文件读取N个字节,然后找到换行符.我认为替换1字节读取可以以某种方式加速该功能.

Ant*_*ala 6

你完全误解了标准的I/O功能.甚至fgetc是缓冲的.readstrace.测试实际呼叫的发布.在我的电脑上,阅读/proc/1/maps:

read(3, "5634f9cf6000-5634f9e44000 r-xp 0"..., 1024) = 1024
read(3, "                   /lib/x86_64-l"..., 1024) = 1024
read(3, "             /lib/x86_64-linux-g"..., 1024) = 1024
read(3, "                   /lib/x86_64-l"..., 1024) = 1024
read(3, ".0.0\n7feb2b2dc000-7feb2b4db000 -"..., 1024) = 1024
read(3, "0-7feb2b8e7000 r--p 00002000 fd:"..., 1024) = 1024
read(3, "00 rw-p 0001a000 fd:00 145004   "..., 1024) = 1024
read(3, "ux-gnu/liblzma.so.5.2.2\n7feb2c1b"..., 1024) = 1024
read(3, "6_64-linux-gnu/libgcrypt.so.20.2"..., 1024) = 1024
read(3, "000 fd:00 135558                "..., 1024) = 1024
read(3, "--p 0000e000 fd:00 136910       "..., 1024) = 1024
read(3, "001e000 fd:00 131385            "..., 1024) = 1024
read(3, "1.1.0\n7feb2da14000-7feb2da15000 "..., 1024) = 1024
read(3, "0 rw-p 00000000 00:00 0 \n7feb2de"..., 1024) = 1024
read(3, "-237.so\n7feb2e492000-7feb2e69100"..., 1024) = 1024
read(3, " \n7feb2ed15000-7feb2ed36000 rw-p"..., 1024) = 637
read(3, "", 1024)                       = 0
Run Code Online (Sandbox Code Playgroud)

read呼叫尝试读取1024字节,而不是只有一个.

该计划是

#include <stdio.h>

int main(void) {
    FILE *f = fopen("/proc/1/maps", "r");
    while (1) {
        char buf[2048];
        if (! fgets(buf, 2048, f)) {
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果1024字节不够,您可以使用setvbuf(3)更改底层缓冲区的大小!