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
|
#include <stdio.h>
#include <stdlib.h>
#define MAXBLOCKS 2000
#define BLOCKSIZE 128
#define NBCOLS 16
#define XSTR(s) #s
#define STR(s) XSTR(s)
int main(int argc, char ** argv)
{
unsigned char buf[BLOCKSIZE];
FILE * fd = NULL;
int i, cnt = 0;
size_t nbBytesOneBlock;
if (argc != 2) {
fprintf(stderr, "Usage: read <file>\n");
exit(EXIT_FAILURE);
}
fd = fopen(argv[1], "rb");
if (!fd) {
fprintf(stderr, "read: cannot open file '%s' for reading\n", argv[1]);
exit(EXIT_FAILURE);
}
/* Lecture par blocs de taille BLOCKSIZE */
while ( ( nbBytesOneBlock = fread(buf, sizeof*buf, sizeof(buf)/sizeof*buf, fd) ) ==
sizeof(buf)/sizeof*buf && cnt < MAXBLOCKS)
{
printf("----- Block no %05d -----\n", cnt+1);
for (i=0; i<sizeof(buf)/sizeof*buf; ++i) {
printf("%02x ", buf[i]);
if ( (i+1) % NBCOLS == 0 ) puts("");
}
fflush(stdout);
++cnt;
}
/*
* Lecture donnees restantes
* On n'a pas réussi à lire BLOCKSIZE éléments => EOF ou erreur de lecture
*/
if ( nbBytesOneBlock && cnt < MAXBLOCKS) {
printf("----- Block no %05d -----\n", cnt+1);
for (i=0; i < (int)nbBytesOneBlock; ++i) {
printf("%02x ", buf[i]);
if ( (i+1) % NBCOLS == 0 ) puts("");
}
fflush(stdout);
/*
* Pourquoi on n'a pas tout lu ? EOF ou erreur ?
*/
if ( feof(fd) && !ferror(fd) ) {
puts("\nread: OK, work done!");
}
else {
fprintf(stderr, "\nread: an error occured while reading '%s'\n", argv[1]);
exit(EXIT_FAILURE);
}
}
else if (cnt >= MAXBLOCKS) {
fprintf(stderr, "\nread: can't read more than %s blocks!\n", STR(MAXBLOCKS) );
exit(EXIT_FAILURE);
}
fclose(fd);
return 0;
} |
Partager