fopen()段错误,文件存在

时间:2014-05-06 17:10:49

标签: c segmentation-fault fopen

我遇到以下问题:虽然文件存在且可访问且路径正确,但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

感谢您的任何想法...

1 个答案:

答案 0 :(得分:1)

根据您的最新评论和代码,指针ime没有分配任何内存。当fscanf尝试写入时,这会导致段错误。

使用

fscanf(dat, "%d %s %c %d", &pid, ime, &stanje, &ppid);因为ime是指针本身。

相关问题