【发布时间】:2014-05-06 17:10:49
【问题描述】:
我遇到了以下问题:fopen() 给出了分段错误,尽管文件存在并且可以访问并且路径是正确的。我有所有必要的包括。
int base(char* dir){
char* pot;
pot=malloc(sizeof(char)*512);
struct dirent *pointerDir;
DIR *pDir;
int pid;
char* ime;
char stanje;
int ppid;
pDir = opendir (dir);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", dir);
return 1;
}
int i=0;
while ((pointerDir = readdir(pDir)) != NULL) {
char* str=malloc(sizeof(char)*20);
i=i+1;
int n=atoi(pointerDir->d_name);
if(n!=0){
strcpy(pot, dir);
sprintf(str, "%d", n);
strcat(pot, str);
strcat(pot, "/");
strcat(pot, "stat");
printf("pot: %s \n", pot);
//open file
FILE* dat=fopen(pot, "r");
if(dat!= NULL){
//do something
}
else{
printf("NULL \n");
}
}
}
closedir (pDir);
return 0;
}
我的输出是:
PID: 1
pot: /proc/1/stat
Segmentation fault
感谢您的任何想法...
【问题讨论】:
-
你没有初始化指针
pot -
所以您在用注释
//do something替换的代码部分中遇到了分段错误,并且您希望不熟悉您的代码的人找出问题所在?我猜你应该写//do something incorrectly,这样可能更有启发性。 -
文件
/proc/1/stat是否需要文件扩展名?例如。/proc/1/stat.txt -
谢谢你的回答,我初始化了指针'pot'。这是缺少的部分,但我认为错误不在这里,因为第一行是打印,没有通过。
printf("test"); fscanf(dat, "%d %s %c %d", &pid, &ime, &stanje, &ppid); fclose(dat); printf("%s %c %d \n", ime, stanje, ppid);
标签: c segmentation-fault fopen