目录条目 C 的 Memchr
有人可以帮我吗?我正在尝试检查每个目录条目的名称中是否存在字母。显然它不起作用。我的主要问题是我在使用 namelist[n]->d_name 作为内存时是否正确使用了 memchr?
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else
{
char * search;
while (n--) {
search= (char*) memchr(namelist[n]->d_name,'a',(sizeof(namelist[n]->d_name)));
if(search !=NULL){
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
char * search;
}
free(namelist);
}
}
Can some on help me out here? I am trying check each directory entry if a letter exists in its name. Obviously it's not working. My main question is am I using the memchr correctly in using the namelist[n]->d_name as a memory?
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, 0, alphasort);
if (n < 0)
perror("scandir");
else
{
char * search;
while (n--) {
search= (char*) memchr(namelist[n]->d_name,'a',(sizeof(namelist[n]->d_name)));
if(search !=NULL){
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
char * search;
}
free(namelist);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码实际上对我有用(在 Win7/CygWin 下):
但是你为什么使用
memchr
?d_name
字段是一个 C 样式字符串,您可以对其执行printf("%s\n",...)
即可证明这一点。您应该使用
strchr
来实现这一点。使用memchr
可能搜索超出字符串末尾的内容,如果在其后的任何垃圾中发现a
,则可能会给出错误结果。如果这对您没有帮助,那么您需要定义短语“显然它不起作用”。换句话说,目录中的所有文件是什么以及您得到什么输出?这将极大地有助于解决这个问题。
That code actually works for me (under Win7/CygWin):
But why are you using
memchr
? Thed_name
field is a C-style string, as evidenced by the fact that you can perform aprintf("%s\n",...)
on it.You should be using
strchr
for that. Usingmemchr
may search beyond the end of the string, possibly giving false results if it findsa
in any junk following that.If that doesn't help you out, then you need to define the phrase "obviously it's not working". In other words, what are all the files in the directory and what output are you getting? That will greatly assist in the resoultion of this problem.
sizeof
和 strlen 不执行同样的事情。但是,正如 @paxdiablo 提到的,你应该只使用 strchr
sizeof
and strlen don't do the same thing.But, as @paxdiablo mentions, you should just use strchr