Salut les C,
J'ai terminer mon premier pseudo programme en C qui affiche le contenue d'un dossier sous Linux analogue a la commande ls -l (sans le propriétaire:groupe), avec différentes options de classement.
J'ai longtemps hésiter a montrer mon code, car il n'y a pas de problème mais je désirerai savoir si vous le voulez bien de me dire ce qui bon ce qui l'est moins et ce qui ne va pas (surtout pour l'allocation mémoire des structures).

Brefs si avez le temps et que vous prenez plaisirs a lire et corriger les codes des débutants merci de bien vouloir me donner quelques conseils pour mes futures réalisations, sinon ne vous prenez pas la tête mon car mon codes est excessivement long pour un post sur un forum (ce qui m'a fait hésiter).

Voici le code entièrement commenter:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
 
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <utime.h>
#include <time.h>
#include <stdlib.h>
 
void print_file_info(char *abspath,char *basename) ; // print one file info line
 
int max_len ;               // contains the greatest filename length ( needed from the exchange algorithms )
void get_max_len(int len) ; // change the max_len value if needed
 
 
struct Files {
    char *name ;
} *files_register;   // filename storing structur
 
struct Files_sorting {
  char *name ;
  int  sort_value ;
} *files_sorting ;  // filename and sort value storing
 
void sort_values_struct(struct Files_sorting *files_sorting,int len) ;          // sort from min to max
void sort_values_struct_reverse(struct Files_sorting *files_sorting,int len) ; // sort from max to min
void set_sort_values_time(struct Files_sorting *files_sorting, struct Files *files_register,int files_counter, int max_len,char *dirname) ; // set the files_register struct with the corresponding sort value in struct Files_sorting
void set_sort_values_size(struct Files_sorting *files_sorting, struct Files *files_register,int files_counter, int max_len,char *dirname) ; // set the files_register struct with the corresponding sort value in struct Files_sorting
 
main(int argc, char *argv[]) {
 
  struct dirent **namelist;
  DIR *dp ;
  struct dirent *dir ;
 
  int files_counter=0 ; // we need to know of many files are in the directory to sort
  char *dirname ;       // directory to list and sort content
  char  *mode ;         // for getting the sort mode given on the cmdline
 
 
  if (argc == 2 )   {
    mode=argv[1] ;
    if ( mode[1] == 'h' ) {
      printf("usage: %s mode [ [-t|-tr] | [-s|-sr] | [-n|-nr] ] absdirpath\n",argv[0]) ;
      printf("\n") ;
      printf(" -h  show this help message\n") ;
      printf("\n") ;
      printf(" mode: files sorting modes\n") ;
      printf("\n") ;
      printf(" -t  sorting by last modification time\n -tr sorting by last modification time reversed\n") ;
      printf(" -s  sorting by size\n -sr sorting by size reversed\n") ;
      printf(" -n  sorting by name\n -nr sorting by name reversed\n") ;
      printf("\n") ;
    }
    exit(EXIT_FAILURE) ;
  }
 
 
  else if (argc == 3) {
    mode=argv[1] ; // store the sorting mode given on cmdline
    if (mode[1] == 't' || mode[1] == 's' || mode[1] == 'n' ) {
      int check_slash ;
      check_slash = strlen(argv[2]) ;
      if ( ! (argv[2][--check_slash] == '/') ) {
	printf("Add the slash at the absdirpath end !!!\n") ;
	exit(EXIT_FAILURE) ;
      }
      else {
	dp=opendir(argv[2]) ;
	dirname=argv[2] ;
 
 
	}
    }
    else {
      printf("usage: %s mode [ [-t|-tr] | [-s|-sr] | [-n|-nr] ] absdirpath\n",argv[0]) ;
      printf("\n") ;
      printf(" -h  show this help message\n") ;
      printf("\n") ;
      printf(" mode: files sorting modes\n") ;
      printf("\n") ;
      printf(" -t  sorting by last modification time\n -tr sorting by last modification time reversed\n") ;
      printf(" -s  sorting by size\n -sr sorting by size reversed\n") ;
      printf(" -n  sorting by name\n -nr sorting by name reversed\n") ;
      printf("\n") ;
      exit(EXIT_FAILURE) ;
    }
  }
 
  else {
    printf("usage: %s mode [ [-t|-tr] | [-s|-sr] | [-n|-nr] ] absdirpath\n",argv[0]) ;
    printf("\n") ;
    printf(" -h  show this help message\n") ;
    printf("\n") ;
    printf(" mode: files sorting modes\n") ;
    printf("\n") ;
    printf(" -t  sorting by last modification time\n -tr sorting by last modification time reversed\n") ;
    printf(" -s  sorting by size\n -sr sorting by size reversed\n") ;
    printf(" -n  sorting by name\n -nr sorting by name reversed\n") ;
    printf("\n") ;
    exit(EXIT_FAILURE) ;
 
  }
 
  printf("Directory content: %s\n",dirname) ;
 
  if ((mode[1] == 't') || (mode[1] == 's') ) {
 
    // sort directory content per modification timestamp or size
    // in this block we fill the files_register structur for later sorting
    if (NULL == (files_register=malloc(256 * sizeof files_register)) ) {
      printf("error files_register malloc\n") ;
      exit(EXIT_FAILURE) ;
    }
 
    if ( NULL == ( files_sorting=malloc(256 * 4 * sizeof files_sorting) ) ) {
      printf("error malloc files_sorting\n") ;
      exit(EXIT_FAILURE) ;
    }
 
    while ( (dir=readdir(dp)) != NULL ) {
 
      if ( files_counter == 0 ) { 
	max_len=strlen(dir->d_name) ;            // we need to know the greatest filename length 
      }
      else {
	get_max_len((int) strlen(dir->d_name)) ; // we need to know the greatest filename length 
      }
 
      files_register[files_counter].name=malloc(sizeof(dir->d_name) * sizeof *files_register->name) ; // memory allocation for storing directory content
 
      snprintf(files_register[files_counter].name,sizeof(dir->d_name),"%s",dir->d_name) ;             // copy filename in files_register structur for storing directory content
      files_counter++ ;
 
      }
 
    closedir(dp) ;
    if (mode[1] == 't') {
      // sort directory content per modification timestamp 
      set_sort_values_time(files_sorting,files_register,files_counter,max_len,dirname) ;
      if (mode[2] == 'r') {
	// reversed modification timestamp sorting
	sort_values_struct_reverse(files_sorting,files_counter) ;
      }
      else {
	// modification timestamp sorting
	sort_values_struct(files_sorting,files_counter) ;
      }
    }
    else if (mode[1] == 's') {
      // sort directory content per file size 
      set_sort_values_size(files_sorting,files_register,files_counter,max_len,dirname) ;
      if (mode[2] == 'r') {
	// reversed file size sorting
	sort_values_struct_reverse(files_sorting,files_counter) ;
      }
      else {
	// file size sorting
	sort_values_struct(files_sorting,files_counter) ;
      }  
    }
 
  free(files_register) ; // free memory from now unneeded files_register structure
  int c ;  
  for (c=0 ; c < files_counter; c++) {
 
    char filepath[255] ;                                     // temporary absfilepath
    char *tmp_file_name=strdup(files_sorting[c].name) ;      // temporary filename with memory allocation return from strdup() 
 
    strcpy(filepath,dirname) ;                               // concatenate absdirpath and filename step 1 
    strcat(filepath,tmp_file_name) ;                         // concatenate absdirpath and filename step 2
    print_file_info(filepath, files_sorting[c].name) ;       // print one result line
    }
 
  }
  else if (mode[1] == 'n') { 
    // sort directory content per filenames
    files_counter=scandir(argv[2], &namelist, 0, alphasort);
    int c,i ;
    if (mode[2] != 'r') {
       // sort directory content per filenames not reversed
      for (c=0 ; c < files_counter ; c++ ) {
 
	char filepath[255] ;                                    // temporary absfilepath
	char *tmp_file_name=strdup(namelist[c]->d_name) ;       // temporary filename with memory allocation return from strdup() 
 
	strcpy(filepath,dirname) ;                              // concatenate absdirpath and filename step 1 
	strcat(filepath,tmp_file_name) ;                        // concatenate absdirpath and filename step 2
	print_file_info(filepath, namelist[c]->d_name) ;        // print one result line
 
      }
    }
    else if (mode[2] == 'r') { 
      // sort directory content per filenames reversed
      if (NULL == (files_register=malloc(256 * sizeof files_register)) ) {
	printf("error files_register malloc\n") ;
	exit(EXIT_FAILURE) ;
      }
      for (c=0,i=files_counter-1 ; c < files_counter ; c++,i-- ) { 
	// fill the the files_register structure with sorting the reversed filename 
	files_register[i].name=malloc(sizeof(namelist[c]->d_name) * sizeof *files_register->name) ; // allocate memory for current files_register.name 
        snprintf(files_register[i].name,sizeof(namelist[c]->d_name),"%s",namelist[c]->d_name) ;     // copy the filename in files_register.name 
      }
      for (c=0; c < files_counter ; c++) {
	char filepath[255] ;                                  // temporary absfilepath
	char *tmp_file_name=strdup(files_register[c].name) ;  // temporary filename with memory allocation return from strdup()
 
	strcpy(filepath,dirname) ;                            // concatenate absdirpath and filename step 1 
	strcat(filepath,tmp_file_name) ;                      // concatenate absdirpath and filename step 2 
	print_file_info(filepath, files_register[c].name) ;   // print one result line
      }
 
    }
  }
  exit(EXIT_SUCCESS) ;
}
 
 
void get_max_len(int len) {
  if ( len > max_len ) {
    max_len=len ;
  }
}
 
 
 
 
void sort_values_struct(struct Files_sorting *files_sorting,int len) {
  int tab_size=len ;
  int pos_min ;       // index from the found value
  int idx_not_sort ;  // index from the not sorted table part
  int min ;           // next value 
 
  int tmp ;           // temporary variable for exchange
  char *tmp_name ;    // temporary variable for exchange
  int i;              // tab iterator
 
  i=0 ;
  while ( i < tab_size) {
    min=files_sorting[i].sort_value ;
    pos_min=i ;
    idx_not_sort=i ;
    while (idx_not_sort < tab_size) {
      // search the lt value in the part of the table not sorted
      if ( files_sorting[idx_not_sort].sort_value < min ) {
	// lt value found
	min=files_sorting[idx_not_sort].sort_value ; // store the table minimal value from his not sorted part  
	pos_min=idx_not_sort ;  // store the table minimal value index from his not sorted part  
      }
      idx_not_sort++ ;
    }
 
    // make the exchange
    tmp=files_sorting[pos_min].sort_value ;                         // set the lt value in tmp 
    tmp_name=files_sorting[pos_min].name ;                          // set the corresponding name in tmp_name
    files_sorting[pos_min].sort_value=files_sorting[i].sort_value ; // set the gt value in the lt value field 
    files_sorting[pos_min].name=files_sorting[i].name ;             // set the gt value in the lt value field 
    files_sorting[i].sort_value=tmp ;                               // set the lt value in the gt value field (at index from tab) 
    files_sorting[i].name=tmp_name ;                                // set the sorting corresponding filename (at index from tab)
    i++ ; // increment the iterator 
  }
}
 
void sort_values_struct_reverse(struct Files_sorting *files_sorting,int len) {
  int tab_size=len ;
  int pos_min ;       // index from the found value
  int idx_not_sort ;  // index from the not sorted table part
  int min ;           // next value 
 
  int tmp ;           // temporary variable for exchange
  char *tmp_name ;    // temporary variable for exchange
  int i;              // tab iterator
 
  i=0 ;
  while ( i < tab_size) {
    min=files_sorting[i].sort_value ;
    pos_min=i ;
    idx_not_sort=i ;
    while (idx_not_sort < tab_size) {
      // search the gt value in the part of the table not sorted
      if ( files_sorting[idx_not_sort].sort_value > min ) {
	// gt value found
	min=files_sorting[idx_not_sort].sort_value ; // store the table minimal value from his not sorted part  
	pos_min=idx_not_sort ;  // store the table minimal value index from his not sorted part  
      }
      idx_not_sort++ ;
    }
 
    // make the exchange
    tmp=files_sorting[pos_min].sort_value ;                         // set the gt value in tmp 
    tmp_name=files_sorting[pos_min].name ;                          // set the corresponding name in tmp_name
    files_sorting[pos_min].sort_value=files_sorting[i].sort_value ; // set the gt value in the gt value field 
    files_sorting[pos_min].name=files_sorting[i].name ;             // set the sorting corresponding filename in the gt value field
    files_sorting[i].sort_value=tmp ;                               // set the gt value in the gt value field (at index from tab) 
    files_sorting[i].name=tmp_name ;                                // set the sorting corresponding filename (at index from tab)
    i++ ; // increment the iterator 
  }
}
 
void set_sort_values_size(struct Files_sorting *files_sorting, struct Files *files_register,int files_counter, int max_len,char *dirname) {
 
  int c ;
  for (c=0 ; c < files_counter; c++) {
 
    struct stat filer ;                                  // struct stat for file info getting 
    char filepath[255] ;                                 // temporary absfilepath
    char *tmp_file_name=strdup(files_register[c].name) ; // temporary filename with memory allocation return from strdup()
    strcpy(filepath,dirname) ;                           // concatenate absdirpath and filename step 1 
    strcat(filepath,tmp_file_name) ;                     // concatenate absdirpath and filename step 2 
    stat(filepath,&filer) ;                              // get file stats
 
    size_t size_cp=max_len ; // for exchanging the names we need the greatest filename value 
 
 
    if ( NULL == (files_sorting[c].name=malloc(size_cp) ) ) {
      // memory allocation for filename in structure 
      printf("file_sort_value.name malloc error\n") ;
      exit(EXIT_FAILURE) ;
    }
 
    snprintf(files_sorting[c].name,size_cp,"%s",files_register[c].name) ; // copy the filename from files_register struct member to files_sorting member
 
    files_sorting[c].sort_value=(int) filer.st_size  ;                    // set the sorting value (here the file size) to files_sorting.sort_value
 
  }
} 
 
void set_sort_values_time(struct Files_sorting *files_sorting, struct Files *files_register,int files_counter, int max_len,char *dirname) {
 
  int c ;
  for (c=0 ; c < files_counter; c++) {
 
    struct stat filer ;                                  // struct stat for file info getting 
    char filepath[255] ;                                 // temporary absfilepath
    char *tmp_file_name=strdup(files_register[c].name) ; // temporary filename with memory allocation return from strdup()
    strcpy(filepath,dirname) ;                           // concatenate absdirpath and filename step 1 
    strcat(filepath,tmp_file_name) ;                     // concatenate absdirpath and filename step 2 
    stat(filepath,&filer) ;                              // get file stats
 
 
    size_t size_cp=max_len ; // for exchanging the names we need the greatest filename value
    if ( NULL == (files_sorting[c].name=malloc(size_cp) ) ) {
      printf("files_sorting.name malloc error\n") ;
      // memory allocation for filename in structure 
      exit(EXIT_FAILURE) ;
    }
    snprintf(files_sorting[c].name,size_cp,"%s",files_register[c].name) ; // copy the filename from files_register struct member to files_sorting member
 
    files_sorting[c].sort_value=(int) filer.st_mtime  ;                   // set the sorting value (here the last modification timestamp) to files_sorting.sort_value
 
  }
} 
 
void print_file_info(char *abspath,char *basename) {
  struct stat filer ; // struct stat from file 
 
  struct tm file_modtime ; // last modification 
  struct tm file_actime  ; // last access
  struct tm file_ctime   ; // state change
 
  stat(abspath,&filer) ; // get file stats
 
  localtime_r(&filer.st_mtime,&file_modtime) ; //get pointer on tm struct for last modification  
  localtime_r(&filer.st_atime,&file_actime)  ; //get pointer on tm struct for last access  
  localtime_r(&filer.st_ctime,&file_ctime)   ; //get pointer on tm struct for state change
  int  file_size_res ;
  int  file_size_calc ;
  int  file_size=(int) filer.st_size ;
  int  unit_idx=0 ;
  char file_size_units[4][3]={{'O','c','\0'},{'K','o','\0'},{'M','o','\0'},{'G','o','\0'}} ; //units for file size
  // compute if a unit conversion is needed
  // and check the size range per imbric conditionnal computing
  if ( (file_size / 8192 ) > 0 ) {
    // the range is Kilo octet
    file_size_res = (file_size / 1024 )  ; // the file size in Kilo octet 
    file_size_calc = ((file_size / 8192 ) * 8) ; // only needed if the range is gt Ko
    unit_idx=1 ; // index from the file_size_units table
    if ( (file_size_calc / 8192 ) > 0 ) {
      // the range is Mega octet
      file_size_res = (file_size_res / 1024 )  ; // the file size in Mega octet (compute with the last value from file_size_res)
      file_size_calc= ((file_size_calc / 8192 ) * 8)  ; // only needed if the range is gt Mo
      unit_idx=2 ; // index from the file_size_units table
    }
    if ( (file_size_calc / 8192 ) > 0 ) {
      // the range is Giga octet
      file_size_res = (file_size_res / 1024 )  ; // the file size in Giga octet (compute with the last value from file_size_res)
      file_size_calc = ((file_size_calc / 8192 ) * 8) ; // not needed 
      unit_idx=3 ; // index from the file_size_units table
    }
  }
  else {
    file_size_res=file_size ;
  }
    // check the directory content type 
    if (S_ISDIR(filer.st_mode) ) {
      printf("%s","d") ;
    }
    else if (S_ISREG(filer.st_mode) ) {
      printf("%s","f") ;
    }
    else if (S_ISLNK(filer.st_mode) ) {
      printf("%s","l") ;
    }
    else {
      printf("%s","-") ;
    }
    // check the user rights
    if ((filer.st_mode) &S_IRUSR ) {
      printf(" %s","r") ;
    }
    else {
      printf(" %s","-") ;
    }
    if ((filer.st_mode) & S_IWUSR) {
      printf("%s","w") ;
    }
    else {
      printf("%s","-") ; 
    }
    if ((filer.st_mode) & S_IXUSR) {
      printf("%s","x") ;
    }
    else {
      printf("%s","-") ; 
    }
    // check the group rights
    if ((filer.st_mode) & S_IRGRP) {
      printf("%s","r") ;
    }
    else {
      printf("%s","-") ;
    }
    if ((filer.st_mode) & S_IWGRP) {
      printf("%s","w") ;
    }
    else {
      printf("%s","-") ;
    }
    if ((filer.st_mode) & S_IXGRP) {
      printf("%s","x") ;
    }
    // check the other rights
    else {
      printf("%s","-") ;
    }
    if ((filer.st_mode) & S_IROTH) {
      printf("%s","r") ;
    }
    else {
      printf("%s","-") ; 
    }
    if ((filer.st_mode) & S_IWOTH) {
      printf("%s","w") ;
    }
    else {
      printf("%s","-") ;
    }
    if ((filer.st_mode) & S_IXOTH) {
      printf("%s","x") ;
    }
    else {
      printf("%s","-") ;
    }
    // print the collected information
    printf(" % 5i %s %i:%02i:%02i %02i:%02i:%02i %s",file_size_res,file_size_units[unit_idx],file_modtime.tm_year+1900,file_modtime.tm_mon,file_modtime.tm_mday,file_modtime.tm_hour,file_modtime.tm_min,file_modtime.tm_sec,basename) ;
 
    printf("\n") ;  
 
}
J'attends vos avis éclairés et bon C a vous.
Merci pour vos réponses.

PS: je ne sais si c'est autoriser de faire ce genre de démarche, le but du forum étant l'entre-aide mais je n'ai pas vraiment le choix si je désire l'opinion de quelqu'un de compétant et je suis ouvert a toutes critiques.