I'm currently traducing the posts in english, my english is not very good, so if you find errors feel free to contact me.
  • tips : best buffer size for read(2), write(2) in *NIX OS

    Je me suis souvent demandé lorsque j’avais besoin de faire des opérations de lecture / écriture dans des progs, quelle était la taille optimale du buffer.
    Après quelques recherches j’ai fini par trouver.
    Il faut se servir de la fonction stat, laquelle nous remplit une struct stat, qui contient un champ intéressant (extrait du man):

    1
    
    u_long st_blksize; /* optimal file sys I/O ops blocksize */

    Voici un petit exemple d’utilisation très minimal qui se contente juste de lire le fichier passé en argument :

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    
    #include <stdio.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <string.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    #include <sys/types.h>
     
    int main(int argc, const char* argv[])
    {
    	int fd;
    	struct stat s;
    	unsigned char* buffer;
     
    	stat(argv[1], &buf);
     
    	if (-1 == (fd = open(argv[1], O_RDONLY)))
    	{
    		perror("open() ");
    		return EXIT_FAILURE;
    	}
    	if (NULL == (buffer = (unsigned char*)malloc(s.st_blksize * sizeof(unsigned char))))
    	{
    		close(fd);
    		perror("malloc() ");
    		return EXIT_FAILURE;
    	}
     
    	unsigned long ul_bytes = 0;
    	while (ul_bytes < s.st_size)
    	{
    		ssize_t bytes_read = read(fd, buffer, s.st_blksize);
    		ul_bytes += bytes_read;
    	}
    	free(buffer);
    	close(fd);
     
    	return EXIT_SUCCESS;
    }