这是我的程序,但编译时我收到“分段错误”消息,没有任何警告。
#include <string>
#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <cstring>
int is_file(char* path) {
struct stat s;
if (( stat(path,&s) == 0 ) && ( s.st_mode & S_IFREG )) return 1; else return 0;
}
int main()
{
DIR *dir;
struct dirent *ent;
char path[] = "../";
if ((dir = opendir (path)) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
char* name = strcat(path, ent->d_name);
if (is_file(name)) printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
我认为这是因为第 20 行的
is_file()
引用,但我不知道为什么以及如何修复它。
strcat()
并不像您想象的那样工作;特别是,它只能将更多字符写入数组中已分配的空间;它无法调整 path[]
的大小来存储额外的字符。 path[]
仅为其分配了 4 个字节的存储空间,因此当您尝试 strcat()
进行路径时,您会超出该数组的末尾,并调用未定义的行为,从而导致分段错误。
由于您使用的是 C++,修复方法很简单:使用
std::string
来存储可变长度字符串数据,而不是 C 风格的字符数组:
#include <string>
#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
#include <cstring>
int is_file(const char* path) {
struct stat s;
if (( stat(path,&s) == 0 ) && ( s.st_mode & S_IFREG )) return 1; else return 0;
}
int main()
{
DIR *dir;
struct dirent *ent;
std::string path = "../";
if ((dir = opendir (path.c_str())) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
std::string name = path + ent->d_name;
if (is_file(name.c_str())) printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
我认为问题之一可能与 strcat 有关。 strcat 只是将源字符串 (ent->d_name) 添加到目标字符串 (path) 的末尾。因此,请尝试为路径分配更多空间。 https://linux.die.net/man/3/strcat