Reputation: 29
I have a linked list that contains a file's path and also a groupID that it belongs to. My program looks for regular files in the current directory and I am trying to iterate through the linked list in order to do something with the linked list. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
typedef struct FileGroups
{
int groupID;
char *path;
struct FileGroups* next;
} FileGroups;
FileGroups *head;
int GroupID = 1;
void insert(char *path)
{
FileGroups *temp;
temp = (FileGroups*)malloc(sizeof(FileGroups));
temp->groupID = GroupID++;
temp->path = malloc(strlen(path)*sizeof(char));
strcpy(temp->path, path);
temp->next = head;
head = temp;
temp = temp->next;
}
void print()
{
FileGroups *temp;
temp = head;
printf("\nLinked list: \n");
while(temp!=NULL)
{
printf("%d %s\n", temp->groupID, temp->path);
temp = temp->next;
}
}
void listFilesRecursively(const char *basePath)
{
char path[1024];
struct dirent *dp;
DIR *dir = opendir(basePath);
if (!dir)
{
return;
}
while ((dp = readdir(dir)) != NULL)
{
if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
{
struct stat sb;
FileGroups *temp;
temp = head;
strcpy(path, basePath);
strcat(path, "/");
strcat(path, dp->d_name);
if(stat(path, &sb) == 0 && S_ISREG(sb.st_mode))
{
insert(path);
while(temp!=NULL)
{
printf("Do something with %s\n", temp->path);
temp = temp->next;
}
printf("\n");
}
else
{
return;
}
}
}
closedir(dir);
}
int main()
{
listFilesRecursively(".");
print();
return 0;
}
This is the output that I get when I run the program:
I'm not sure if I am traversing through the linked list correctly because it seems as though it is printing out "Do something" iteratively but with each pass through the loop, it seems to add an extra call to printf("Do something\n");
to whatever the previous file paths were along with the current one that it is on, I want it to just do something with the current file path that is being added to the list. It also seems to not printf("Do something\n");
during its first loop as there is a newline before we even print out "Do something" with the first file in the directory and the last thing is it does not do anything with the last file in the directory which is ./testing.txt
. Thank you in advance for your suggestions and advice!
Upvotes: 0
Views: 361
Reputation: 238
Its because you are looping through the entire list while you are building it. Either print the list after you looped through the directory contents, or better yet, only print a single item within the directory search loop.
while(temp!=NULL)
{
printf("Do something with %s\n", temp->path);
temp = temp->next;
}
should just be :
printf("Do something with %s\n", path);
Upvotes: 1