隐藏bug

YEZI329883153 2011-04-28 11:26:41
帮忙看下这段代码:
功能:在指定的目录中,查找匹配的文件。如果找到该文件则返回true,否则返回false
参数:dirName:指定的目录
confName:指定的文件名
函数体如下:

bool find_eop_card_conf_file(char *dirName,char *confName)
{

DIR *dir_p;
struct dirent *dirent_p;
dir_p = opendir(dirName);
while((dirent_p=readdir(dir_p))!=NULL)
{
if(0!=strstr(dirent_p->d_name,confName))
{
closedir(dir_p);
return true;
}
}
closedir(dir_p);
}


问题:在大量的测试中发现,有时候这个函数会找错。比如某个文件A其实不存在,确误查为存在。环境:比如这个文件下下存在slot_01_a.conf slot_02_a.conf. 但是查找slot_03_a.conf有时候会说存在。这种概率很小,但是有时候确实会出现。
但是代码我真的看不出来什么问题。求救。
...全文
115 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2011-04-29
  • 打赏
  • 举报
回复
strstr
char *strstr( const char *string, const char *strCharSet );

Find a substring.
returns a pointer to the first occurrence of strCharSet in string, or NULL if strCharSet does not appear in string. If strCharSet points to a string of zero length, the function returns string.
--------------------
_stricmp
int _stricmp( const char *string1, const char *string2 );

The return value indicates the relation of string1 to string2 as follows.
Return Value Description
< 0 string1 less than string2
0 string1 identical to string2
> 0 string1 greater than string2


Perform a lowercase comparison of strings.
=====================
strstr是不忽略大小写判断string中是否包含strCharSet
比如"ABC"中包含"ABC"也包含"AB"、"BC"、"A"、"B"、"C"、尤其是包含"";但不包含"abc"

stricmp是忽略大小写比较string1和string2
比如"ABC"和"AB"不同;但和"abc"相同

bluesky12312388 2011-04-28
  • 打赏
  • 举报
回复
因为你用的是strstr(dirent_p->d_name,confName)
改成strncmp就不会了。
bdmh 2011-04-28
  • 打赏
  • 举报
回复
查找文件,为什么不用findfirs,findnext这些api呢
YEZI329883153 2011-04-28
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 zhao4zhong1 的回复:]
if(0!=strstr(dirent_p->d_name,confName))
改为
if(0==stricmp(dirent_p->d_name,confName))
[/Quote]

我现在是有方法可以改正,但是我不知道为什么用strstr会出现这个问题,这个可以解释一下吗。什么情况下strstr会出这种问题呢
pathuang68 2011-04-28
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 zhao4zhong1 的回复:]

if(0!=strstr(dirent_p->d_name,confName))
改为
if(0==stricmp(dirent_p->d_name,confName))
[/Quote]

++
赵4老师 2011-04-28
  • 打赏
  • 举报
回复
if(0!=strstr(dirent_p->d_name,confName))
改为
if(0==stricmp(dirent_p->d_name,confName))
赵4老师 2011-04-28
  • 打赏
  • 举报
回复
strstr改为stricmp

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧