Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strtok function

Status
Not open for further replies.

brent123

MIS
Mar 21, 2006
29
0
0
US
I'm trying to parse the filenames in a directory into file name and extension. I'm using strtok to do the parsing but I keep getting an Segmentation fault. My code is below. What am I doing wrong?

Thanks,

#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char *argv[]) {
DIR *dp;
struct dirent *dirp;
struct stat buf;
char *str1;
char *filename;


if ((dp = opendir(argv[1])) == NULL)
printf("can't open %s", argv[1]);
while ((dirp = readdir(dp)) != NULL){
filename = dirp->d_name;
str1 = strtok(filename,".");
printf("%s\n",str1);
str1 = strtok(NULL,".");}

closedir(dp);
exit(0);
}
 
1. Please use [code][/code] tags when posting code.

2. The first two entries returned by readdir() are usually "." and ".." (the current and parent directories). Trying to do strtok() on those immediately returns a NULL pointer, and thus your printf() blows up.

Also, I'd be wary of modifying the storage which is being managed by readdir(). Copy the filename to a temporary string of your own, then strtok() that.



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
If the filename doesn't have a "." delimenter in it, will this cause a segmentation fault error.
 
You should always check the return value of strtok() (or any function for that matter) to see if an error occurred.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top