2013-10-28 204 views
3

基本上这段代码给了我目录中的文件的名称....但我需要得到他们的路径,而不是..我尝试使用函数realpath()。但我错误地使用了它(我在代码中显示我想使用它)。任何想法如何解决它?还有一件事:它给了我只有子目录的名字,但基本上我需要得到他们的文件的路径too.Thanks。获取文件的完整路径C

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

int main (int c, char *v[]) { 
    int len, n; 
    struct dirent *pDirent; 
    DIR *pDir; 
    int ecode=0; 
    struct stat dbuf; 
    for (n=1; n<c; n++){ 
     if (lstat(v[n], &dbuf) == -1){ 
      perror (v[n]); 
      ecode ++; 
     } 
     else if(S_ISDIR(dbuf.st_mode)){ 
      printf("%s is a directory/n ", v[n]); 
     } 
     else{ 
      printf("%s is not a directory\n", v[n]); 
     } 
    } 
    if (c < 2) { 
     printf ("Usage: testprog <dirname>\n"); 
     return 1; 
    } 
    pDir = opendir (v[1]); 
    if (pDir == NULL) { 
     printf ("Cannot open directory '%s'\n", v[1]); 
     return 1; 
    } 

    while ((pDirent = readdir(pDir)) != NULL) { 
     // here I tried to use realpath() 
     printf ("[%s]\n", realpath(pDirent->d_name)); 
    } 
    closedir (pDir); 
    return 0; 
} 
+0

'realpath'应该有效,你看到了什么,你期望什么? –

+0

我想我在那里用错了...我可以说像realpath(pDirent-> d_name),因为我在代码中使用?我认为不......我添加了char actualpath [PATH_MAX];然后尝试像printf(“[%s] \ n”,realpath(actualpath,pDirent-> d_name));但它仍然无法工作.... –

+0

我的男人realpath说:'char * realpath(const char *限制file_name,char *限制resolved_name);'。 –

回答

2

所有你需要的是将第二个参数添加到实际路径,因为它需要一个缓冲区来写入。我建议你从printf语句中抽出一行并给它自己的行。 realpath()可以返回一个char *,但它的设计目的不是这样。

#include <limits.h>  //For PATH_MAX 

char buf[PATH_MAX + 1]; 
while ((pDirent = readdir(pDir)) != NULL) { 
    realpath(pDirent->d_name, buf); 
    printf ("[%s]\n", buf); 
} 

这似乎是在我的系统上正确显示完整路径。

+3

如果你不是'cwd'进入包含这些文件的目录,'realpath'是否像这样工作? – joshperry