#define _POSIX_C_SOURCE 1 #include #include #include #include #include #include #include "charger.h" int charger(char *nom, char **tampon) { struct stat caracteristiques; int nombre_de_caracteres_a_lire; int nombre_de_caracteres_par_lecture; char *position_tampon; int nombre_de_caracteres_deja_lus = 0; int fd = open(nom, O_RDONLY); if (fd == -1 || fstat(fd, &caracteristiques) == -1) { perror(nom); exit(EXIT_FAILURE); } if (!S_ISREG(caracteristiques.st_mode)) { fprintf(stderr, "%s n'est pas un fichier ordinaire\n", nom); exit(EXIT_FAILURE); } nombre_de_caracteres_a_lire = caracteristiques.st_size; if (nombre_de_caracteres_a_lire == 0) return 0; *tampon = malloc(nombre_de_caracteres_a_lire); if (*tampon == NULL) { perror(NULL); exit(EXIT_FAILURE); } position_tampon = *tampon; if (nombre_de_caracteres_a_lire > SSIZE_MAX) nombre_de_caracteres_par_lecture = SSIZE_MAX; else nombre_de_caracteres_par_lecture = nombre_de_caracteres_a_lire; for (;;) { int n = read(fd, position_tampon, nombre_de_caracteres_par_lecture); if (n == -1) { perror(nom); exit(EXIT_FAILURE); } nombre_de_caracteres_deja_lus += n; position_tampon += n; if (nombre_de_caracteres_deja_lus == nombre_de_caracteres_a_lire) break; } close(fd); return nombre_de_caracteres_a_lire; }