How do you list files in a directory?


Unfortunately, there is no built-in function provided in the C language such as dir_list() that would easily provide you with a list of all files in a particular directory. By utilizing some of C's built-in directory functions, however, you can write your own dir_list() function.

First of all, the include file dos.h defines a structure named find_t, which represents the structure of the DOS file entry block. This structure holds the name, time, date, size, and attributes of a file. Second, your C compiler library contains the functions _dos_findfirst() and _dos_findnext(), which can be used to find the first or next file in a directory.

The _dos_findfirst() function requires three arguments. The first argument is the file mask for the directory list. A mask of *.* would be used to list all files in the directory. The second argument is an attribute mask, defining which file attributes to search for. For instance, you might want to list only files with the Hidden or Directory attributes. The last argument of the _dos_findfirst() function is a pointer to the variable that is to hold the directory information (the find_t structure variable).

The second function you will use is the _dos_findnext() function. Its only argument is a pointer to thefind_t structure variable that you used in the _dos_findfirst() function. Using these two functions and the find_t structure, you can iterate through the directory on a disk and list each file in the directory. Here is the code to perform this task:

#include <stdio.h>
#include <direct.h>
#include <dos.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
typedef struct find_t FILE_BLOCK;
void main(void);
void main(void)
     FILE_BLOCK f_block;      /* Define the find_t structure variable */
     int ret_code;     /* Define a variable to store the return codes */
     printf("\nDirectory listing of all files in this directory:\n\n");
     /* Use the "*.*" file mask and the 0xFF attribute mask to list
        all files in the directory, including system files, hidden
        files, and subdirectory names. */
     ret_code = _dos_findfirst("*.*", 0xFF, &f_block);
     /* The _dos_findfirst() function returns a 0 when it is successful
        and has found a valid filename in the directory. */
     while (ret_code == 0)
          /* Print the file's name */
          /* Use the _dos_findnext() function to look
             for the next file in the directory. */
          ret_code = _dos_findnext(&f_block);
     printf("\nEnd of directory listing.\n");


© 2017