i am trying to list all files in the directory with .txt extension but in vain.please help me with the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
char *p;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
p=strtok(dir->d_name,".");
p=strtok(NULL,".");
if(p=="txt")
printf("%s\n",dir->d_name);
}
closedir(d);
}
return(0);
}
|
Last edited on
on line 16: You compare to [c string] pointer. Use strcmp instead
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
|
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
DIR *d;
char *p;
int ret;
struct dirent *dir;
d = opendir(".");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
p=strtok(dir->d_name,".");
p=strtok(NULL,".");
ret=strcmp(p,"txt");
if(ret==0)
printf("%s",dir->d_name);
}
closedir(d);
}
return(0);
}
|
now there's a run time error
Last edited on