Reputation: 3
I wrote a program that reads directories. It reads only up to level 2 of the given directory.
void
readDir (char *pth)
{
char path[1000];
strcpy (path, pth);
DIR *dp;
DIR *dp2;
struct dirent *files;
struct dirent *files2;
if ((dp = opendir (path)) == NULL)
perror ("dir\n");
char newp[1000];
struct stat buf;
while ((files = readdir (dp)) != NULL)
{
if ((strcmp (files->d_name, ".") && strcmp (files->d_name, "..")))
{
strcpy (newp, path);
strcat (newp, "/");
strcat (newp, files->d_name);
printf ("%s\n", newp);
if ((dp2 = opendir (newp)) == NULL)
perror ("dir\n");
while ((files2 = readdir (dp2)) != NULL)
{
printf ("%s\n", files2->d_name);
if ((strcmp (files2->d_name, ".")
&& strcmp (files2->d_name, "..")))
{
strcat (newp, "/");
strcat (newp, files2->d_name);
//printf("%s\n",newp);
CheckOutput (newp);
}
}
}
}
}
Example of directoreis arrangement: (In each of the users directory there is one text file.)
Head -> user1 -> a.txt
-> user2 -> b.txt
-> user3 -> c.txt
It worked fine once, but then something weird happened: I copied txt file pasted, and deleted and it printed some weird directories like:
/home/Desktop/Head/user/a.txt~
/home/Desktop/Head/user/a.txt~/b.txt~
And I have no idea why. Can anyone help me?
Upvotes: 0
Views: 67
Reputation: 384
You should begin with initializing newp[1000] to zero with something like this :
char newp[1000] = {0};
You have problem in your loop because you use newp for both the path and the name of the files, which are two different things you have to deal with. Indeed you will have a problem at opening ./user1 then ./user2 since you overwrite newp with ./user1/a.txt~ and never cleans it.
By the way, the ~ affair may just be a backup file in the directory you launch your program with. Depending on what OS you're working on, readdir may return you hidden files from its very first call, which is most probably the case here since your file starts with an 'a'.
Find a way of creating the correct paths in your while's loop and do ls -a in your current directory.
Upvotes: 0
Reputation: 640
The tilde at the end of the filename means that this is a backup file. My assumption is that the problem is not in your code, but in the editor you used to edit the files. Editors, such as gedit
for example, leave a backup file which is denoted by a ~
sign at the end. You should try closing the editor and running the program again.
Upvotes: 1