#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的問題 - 我在這裏做錯了什麼?
請重新格式化您的代碼,您的文本是一個完整的災難。沒有人可以幫助你,如果他們不能讀你的問題。 – GWW 2010-10-02 03:30:57
除了重新格式化之外,您可以嘗試提供更多信息嗎?你卡在哪裏,出了什麼問題? – ssube 2010-10-02 03:32:06
你失敗的症狀是什麼?你正在檢查的目錄也可能有幫助。 'ls -a dir' – nategoose 2010-10-02 03:37:00