Faustas - Programming, Projects, Psychology and Faust
Do not use this version. I will rewrite it with much more memory save sub functions and additional checks.
I wrote the following program to analyze directory structures and count the number of lines of the different file types. Additionally, it counts the number of specific file types in the traversed structure and prints the results to the screen.
I named the program structan. This is a simple acronym for structure analysis and was chosen simply because I could think of no other name.
This program is far away from being optimally programmed. Surely there are countless ideas for improvement, which could be implemented. I created it out of interest and will certainly make some improvements over time. Currently, it fulfills its purpose. If you want to modify the program, feel free to do so and I would be happy to see your improvements.
In addition, I am sure that you could be just as fast with a shell script, and also would have to write less code.
The following function is the key function in the structan.c file and traverses through the directory structure. If it finds a file, the type of the file and the number of lines will be stored.
void traverse(DIR *dir, string path) { struct dirent *dir_info; // file info DIR *directory; string new_path; while( (dir_info = readdir(dir)) != NULL ) { // ignore ".", ".." and files that start with a dot if ((dir_info != NULL) && (dir_info->d_name != NULL) && (dir_info->d_name[0] != '.')) { // allocate memory new_path = malloc(strlen(path) + strlen(dir_info->d_name) + strlen("/") + 1); // construct the new path strcat(new_path, path); strcat(new_path, "/"); strcat(new_path, dir_info->d_name); // step into the new directory if ( (directory = opendir(new_path)) != NULL ) { traverse(directory, new_path); } // add the file to the types array add_to_types(new_path, strrchr(new_path, '.')); }// if }// while }// traverse
These are the definitions out of the structan.h header file.
#define NUMBER_OF_TYPES 100 typedef char * string; // used arrays for the storage of the types and line counts string types[NUMBER_OF_TYPES]; int type_count[NUMBER_OF_TYPES]; int type_lines[NUMBER_OF_TYPES]; /** * Add the type to the type array, count the occurence of * the specific type and count the number of lines, found * in the file. */ void add_to_types(string path, string type); /** * Count the number of lines found in the file. */ int count_lines(string path); /** * Initialize the arrays for the storage of the type relevant data. */ void init_arrays(); /** * Show the results of the program. */ void show_types(); /** * Traverse through the file structure. */ void traverse(DIR *dir, string path);
The files are attached at the end of this article. Just store the attached .zip file and unzip it.
If you want to compile the program, just type:
gcc -o structan structan.c
To run the program:
./structan directory-path
| Attachment | Size |
|---|---|
| structan.zip | 2.81 KB |