2013-09-23 39 views
-1

我在C中有下面的代碼。我在FreeBSD上運行它。我編譯它爲cc -o bbb bb.c。然後運行並獲得輸出stat給沒有這樣的文件或目錄

$ ./bbb 
-1  
stat: No such file or directory 

這是代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <fcntl.h> 
#include <string.h> 
#include <sys/types.h> 
#include <dirent.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <string.h> 


int main() { 
    struct stat *st; 
    int stat_code =0; 
    stat_code = stat("/", st); 
    printf("%d\n", stat_code); 
    perror("stat"); 
    return 0; 
} 
+3

考慮到你將未初始化的指針傳遞給stat,它對你來說太過分了,可能會更糟糕。 –

+0

嗯,我通過「/」不知道如何可以未初始化? – Alexandr

+1

@Alexandr:不*指針*。另一個。 –

回答

0

這個函數原型爲STAT()從人2統計

INT統計(常量char * path,struct stat * buf);

由於結構變量的地址需要在stat()函數中傳遞,因此您的代碼將會出現段錯誤。

代碼:

#include <stdio.h> 
    #include <stdlib.h> 
    #include <sys/types.h> 
    #include <sys/stat.h> 
    #include <unistd.h> 

    int main() { 
     struct stat st; 
     int stat_code =0; 
     stat_code = stat("test.txt", &st); 
     printf("%d\n", stat_code); 
     perror("stat"); 
     return 0; 
    } 

上面會幫你的。僅供參考

人2統計

0

int stat(const char *restrict path, struct stat *restrict buf);

stat()功能應得到有關命名的文件信息,並把它寫在區域指向的參數buf。 path參數指向命名文件的路徑名。

在您的代碼中stat("/", st);是僅用於目錄的路徑。

相關問題