linux 下的一个小程序,请高手帮忙看看
来源:百度知道 编辑:UC知道 时间:2024/06/01 10:04:36
程序如下:
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir (char* dir)
{
DIR* dp;
struct dirent* entry;
if ( (dp = opendir(dir) ) == NULL )
{
fprintf (stderr, "cannot open directory: %s\n", dir);
return;
}
while ( (entry = readdir(dp) ) != NULL );
{
printf ("%s\n", entry->d_name);
}
closedir (dp);
}
int main ()
{
printf ("Directory scan of /home :\n");
printdir ("/home");
printf ("done.\n");
exit(0);
}
用gcc编译成功,但运行时显示断错误,错误出现在while处,请大虾们帮忙看看到底错在哪里??谢了先
忘了说了,此程序是用来遍历一个文件夹下的所有文件
改正一下是“段错误”
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir (char* dir)
{
DIR* dp;
struct dirent* entry;
if ( (dp = opendir(dir) ) == NULL )
{
fprintf (stderr, "cannot open directory: %s\n", dir);
return;
}
while ( (entry = readdir(dp) ) != NULL );
{
printf ("%s\n", entry->d_name);
}
closedir (dp);
}
int main ()
{
printf ("Directory scan of /home :\n");
printdir ("/home");
printf ("done.\n");
exit(0);
}
用gcc编译成功,但运行时显示断错误,错误出现在while处,请大虾们帮忙看看到底错在哪里??谢了先
忘了说了,此程序是用来遍历一个文件夹下的所有文件
改正一下是“段错误”
建议楼主检查一下
库函数readdir()的返回值,以及结构struct dirent的成员d_name的含义。
“运行时显示断错误”表示程序访问了非法的指针。根据程序来看,总共存在三个指针:dp、entry和d_name。逐一排除吧。