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!

strcmp problem

Status
Not open for further replies.

TheObserver

Programmer
Mar 26, 2002
91
0
0
US
I am doing a strcmp on a filename returned from a directory pointer. However, the comparisons don't seem to work, and the program flows straight through (and thus all of the logic evaluates to "true") until it hits the exit(1) in the code below. Any ideas on why the logic isn't working right?

while ( (direntp = readdir( dirp )) != NULL )
{
printf("\n\nhello\n\n\n");
if ( strcmp ( direntp->d_name, "." ) == 0 ||
strcmp ( direntp->d_name, ".." ) == 0 )
{
if(consoleout)
{
printf("Invalid input file.\n");
}
}
// if((strcmp(direntp->d_name, ".") != 0) && (strcmp(direntp->d_name, "..") != 0))
else
{
printf("\n\nframe file: %s\n",direntp->d_name);
printf("strcmp %i\n",strcmp(direntp->d_name,"."));
printf("strcmp %i\n",strcmp(direntp->d_name,".."));

//test our first argument and see what it is.
if ((ffptr = fopen( direntp->d_name, "r" )) == NULL)
{
if(consoleout)
{
printf("\nError opening input frame file: %s\n",direntp->d_name);
}
exit(1);
}

//do stuff

}



I get the following output to my console:
______
% ./test /home/


hello




frame file: .
strcmp -55
strcmp -68

Error opening input frame file: .
______

Thanks for your time.
 
strcmp will fail if one string is longer than the other being compared.
So comparing "." against an entire directory string such as "./thisdir/thisfile.ext" will fail even though the second string starts with a dot.

 
If you do want to compare the first n characters of two strings, consider using strncpy():

int strncpy( const char *s1, const char *s2, size_t n );
 
You write:
"if ( strcmp ( direntp->d_name, "." ) == 0 "

As I understand "direntp->d_name" is a structure type.
You can not use strcmp on a structure type because it only contains addresses. So your comparing a addres with a dot.

You have to use memcmp for this. Your code would be like:

"if (memcmp(direntp->d_name, ".", sizeof(direntp->d_name)) == 0)

 
Kocky,
You are incorrect.
If you would take a look at the definition for
the direntp structure and the readdir function def
you will see that this is a pointer to a character
array and is perfectly legal.


 
if ( strcmp ( direntp->d_name, "." ) == 0 ||
strcmp ( direntp->d_name, ".." ) == 0 )


try changing the above to

if (( strcmp ( direntp->d_name, "." ) == 0) ||
(strcmp ( direntp->d_name, ".." ) == 0) )

or

if (!strcmp ( direntp->d_name, ".") ||
!strcmp ( direntp->d_name, ".." ) )

maybe yes, maybe no

tomcruz.net


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top