【发布时间】:2013-12-02 03:38:35
【问题描述】:
我是这个论坛的新手,所以请多多包涵。
我目前正在编写一个备份特定文件的程序,每次备份时都会在文件名中添加一个日期和时间戳。在这个阶段,我正在编写一个函数,它将识别当前工作目录中的所有文件,然后将其读入一个数组,稍后将备份这些文件中的每一个。备份工作正常。
我遇到的问题是,每次尝试将文件夹名称(作为字符串)传递给我的函数时,调试器都会出现分段错误:
程序收到信号SIGSEGV,分段错误。 备份所有文件中的 0x0000000000400b48 ( dirname=) 在 processing.c:52 52 {
backupAllFiles() 函数写在 processing.c 源文件中(它是一个多源文件项目)。这是主要关注的代码的 sn-p:
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <getopt.h>
void backupAllFiles(char *dirname)
{
int numfiles = 0;
char allFiles[MAXPATHLEN][MAXPATHLEN];
DIR *dirp;
struct dirent *dp;
dirp = opendir(dirname);
if(dirp == NULL)
{
fprintf(stderr, "Could not open: %s.\n",dirname);
exit(EXIT_FAILURE);
}
while((dp = readdir(dirp)) != NULL)
{
struct stat stat_buffer;
if(stat(allFiles[numfiles], &stat_buffer) != 0)
{
fprintf(stderr,"An error occurred while reading the directory: %s\n",dirname);
}
else if(S_ISREG(stat_buffer.st_mode))
{
sprintf(allFiles[numfiles], "%s%s", dirname, dp->d_name);
}
numfiles++;
}
for(int i = 0; i < numfiles; i++)
{
fprintf(stderr,"All the files are (%i) %s.\n",i ,allFiles[i]);
}
}
int main(int argc, char *argv[])
{
fprintf(stderr, "Entered main, passing argument %s to backupAllFiles()\n",argv[1]);
backupAllFiles(argv[1]);
return 0;
}
请注意,这还不是主程序的一部分,这只是一个单独的段,用于单独的测试。
我真的很困惑为什么会发生段错误,我已经尝试了 strdup 用于 argv[1],但无济于事。
感谢所有帮助。 :)
附:会有额外的不必要的包含,这是程序的其余部分,我懒得找到专门适用于这个功能的。
【问题讨论】:
-
MAXPATHLEN是什么?你的堆栈溢出了吗? -
if(stat(allFiles[numfiles], &stat_buffer) != 0)此时 allFiles[][] 仍未初始化。 -
MAXPATHLEN 是在其中一个标头中提供的常量 #include
它只是限制任何文件位置的最大路径长度。 -
allFiles 已在函数的早期初始化,段错误发生在任何初始化完成之前,我使用 fprintf(stderr,"Started function backupAllFiles\n") 作为函数的第一行和它永远不会到达它,它会在此之前终止程序。
-
allFiles has been initialised earlier in the function,在哪一行?
标签: c segmentation-fault