Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation avec
Le langage C
Voir le programme détaillé

Fonction fstat - Entête <sys/stat.h>

Entête à inclure

#include <sys/stat.h>

Fonction fstat

int fstat( int fildes, struct stat * buf );

La fonction fstat récupère les métadonnées d'un fichier déjà ouvert, à partir de son descripteur POSIX.

Paramètres

Valeur de retour

En cas de succès, la fonction renvoie 0. En cas d'erreur, elle renvoie -1 et positionne errno.

Exemple de code

L'exemple suivant ouvre un fichier avec open, puis récupère sa taille avec fstat.

 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 
#define _POSIX_C_SOURCE 200809L

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

int main(int argc, char * argv[]) {

    if (argc != 2) {
        printf("Usage: %s file\n", argv[0]);
        return EXIT_FAILURE;
    }

    int fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror("open");
        return EXIT_FAILURE;
    }

    struct stat informations;
    if (fstat(fd, &informations) == -1) {
        perror("fstat");
        close(fd);
        return EXIT_FAILURE;
    }

    printf("Taille : %ld octets\n", (long) informations.st_size);
    close(fd);
    return EXIT_SUCCESS;
}
Utilisation de fstat

Conformité

Fonction définie par POSIX.

Sujets connexes

stat
fstatat
struct stat
<unistd.h>


Vous êtes un professionnel et vous avez besoin d'une formation ? Programmation avec
Le langage C
Voir le programme détaillé