2010-10-02 126 views
1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <dirent.h> 

static char *dup_str(const char *s) 
{ 
    size_t n = strlen(s) + 1; 
    char *t = (char*) malloc(n); 
    if (t) 
    { 
     memcpy(t, s, n); 
    } 
    return t; 
} 

static char **get_all_files(const char *path) 
{ 
    DIR *dir; 
    struct dirent *dp; 
    char **files; 
    size_t alloc, used; 
    if (!(dir = opendir(path))) 
    { 
     goto error; 
    } 
    used = 0; 
    alloc = 10; 
    if (!(files = (char**) malloc(alloc * sizeof *files))) 
    { 
     goto error_close; 
    } 

    while ((dp = readdir(dir))) 
    { 
     if (used + 1 >= alloc) 
     { 
      size_t new_thing = alloc/2 * 3; 
      char **tmp = (char**) realloc(files, new_thing * sizeof *files); 
      if (!tmp) 
      { 
       goto error_free; 
      } 
      files = tmp; 
      alloc = new_thing; 
     } 
     if (!(files[used] = dup_str(dp->d_name))) 
     { 
      goto error_free; 
     } 
     ++used; 
    } 
    files[used] = NULL; 
    closedir(dir); 
    return files; 
error_free: 
    while (used--) 
    { 
     free(files[used]); 
    } 
    free(files); 
error_close: 
    closedir(dir); 
error: 
    return NULL; 
} 

int main(int argc, char **argv) 
{ 
    char **files; 
    size_t i; 

    if (argc != 2) 
    { 
     fprintf(stderr, "Usage: %s DIRECTORY\n", argv[0]); 
     return EXIT_FAILURE; 
    } 
    files = get_all_files(argv[1]); 

    if (!files) 
    { 
     fprintf(stderr, "%s: %s: something went wrong\n", argv[0], argv[1]); 
     return EXIT_FAILURE; 
    } 

    for (i = 0; files[i]; ++i) 
    { 
     FILE *fp; 
     if((fp = fopen(files[i],"r"))==NULL) 
     { 
      printf("error cannot open file\n"); 
      exit(1); 
     } 
     fclose(fp); 
    } 
    for (i = 0; files[i]; ++i) 
    { 
     free(files[i]); 
    } 
    free(files); 
    return EXIT_SUCCESS; 
} 

我剛剛收到「錯誤無法打開文件」。關於fopen的問題 - 我在這裏做錯了什麼?

+2

請重新格式化您的代碼,您的文本是一個完整的災難。沒有人可以幫助你,如果他們不能讀你的問題。 – GWW 2010-10-02 03:30:57

+3

除了重新格式化之外,您可以嘗試提供更多信息嗎?你卡在哪裏,出了什麼問題? – ssube 2010-10-02 03:32:06

+1

你失敗的症狀是什麼?你正在檢查的目錄也可能有幫助。 'ls -a dir' – nategoose 2010-10-02 03:37:00

回答

4

如果我調用你的程序通過它/tmp作爲參數。

files = get_all_files(argv[1]); 

將返回所有的文件/tmp但是當你這樣做:

​​

你正試圖從當前工作目錄中打開這些文件。但它們出現在您作爲參數傳遞的目錄中,導致您的fopen失敗。

爲了解決這個問題

  • 你前綴目錄名文件 被打開。或
  • 您可以使用chdir更改您的密碼,然後執行fopen s。
+0

是的。感謝指針 – user222094 2010-10-02 03:44:22

+1

另外還有一個名爲'strdup'的庫函數:http://linux.die.net/man/3/strdup它完全符合你的'dup_str'函數的功能。 – codaddict 2010-10-02 03:58:45

+1

這也可以幫助您解決任何未來的錯誤,如果你。 (1)打印出你不能打開的文件的名字,(2)打印出錯的原因(例如,用sterrror()) – 2010-10-02 04:16:28

1

一對夫婦的問題,我認爲:

  1. readdir()返回子目錄的路徑,甚至喜歡的條目 「」和「..」。
  2. 您嘗試打開返回的文件,但無論當前目錄是什麼 - 您需要將路徑連接到要打開的文件名。
相關問題