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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
/*
* Attention le code source ci-dessous
* est susceptible de contenir des erreurs
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void ){
/*
* Définition des variables
*/
size_t i = 0;
FILE *p = NULL;
extern int errno;
char c_str = '\0';
size_t sZFile = 0;
char *ptr_buff = NULL;
errno = 0;
if( NULL == (p = fopen("main.c", "r") ) ){
(void)fprintf(stderr,
"Erreur fopen (%d)\t:%s\n", errno,
strerror(errno) );
return EXIT_FAILURE;
}
/*
* Positionnement en fin de fichier
*/
if( 0 != fseek(p, 0L, SEEK_END) ){
(void)fclose(p);
p = NULL;
(void)fprintf(stderr,
" Erreur fseek (%d)\t:%s\n", errno,
strerror(errno) );
return EXIT_FAILURE;
}
/*
* Acquisition de la position courante
* dans le fichier en nombre d'octets.
*/
if( -1 == (sZFile = ftell(p) ) ){
(void)fclose(p);
p = NULL;
(void)fprintf(stderr,
"Erreur ftell (%d)\t:%s\n", errno,
strerror(errno) );
return EXIT_FAILURE;
}
/*
* Positionnement en début de fichier
*/
if( 0 != fseek(p, 0L, SEEK_SET) ){
(void)fclose(p);
p = NULL;
(void)fprintf(stderr,
"Erreur fseek (%d)\t:%s\n", errno,
strerror(errno) );
return EXIT_FAILURE;
}
/*
* Allocation dynamique de la mémoire
*/
if( NULL ==
( ptr_buff = malloc( sZFile * sizeof *ptr_buff) ) ){
(void)fclose(p);
p = NULL;
(void)fprintf(stderr,
"Erreur Allocation (%d)\t:%s\n",
errno, strerror(errno) );
return EXIT_FAILURE;
}
(void)memset( ptr_buff, 0, sZFile );
for( ; EOF != (c_str = fgetc(p) );
*(ptr_buff+(i++)) = c_str )
;
/*
* close du fichier
*/
(void)fclose( p );
p = NULL;
/*
* Affichage du contenu
*/
(void)fprintf(stderr, "%s\n", ptr_buff );
/*
* Free du pointeur
*/
free( ptr_buff );
ptr_buff = NULL;
return EXIT_SUCCESS;
} |
Partager