你为什么得到input_file等于NULL是很明显的,因为没有你想要打开的文件在当前目录中。
假设例如考虑您的工作目录(这是你在哪里编译你的C程序)
/home/student/Myfolder
让我们假设你要打开“输入”文件夹,有两个文件1.txt的和2.txt。
编译什么编译器为fopen()函数后是它搜索文件
/home/student/Myfolder/1.txt
但实际的路径是
/home/student/Myfolder/Input/1.txt
我希望你明白这一点。为了克服这个问题,你必须得到当前工作目录cwd()函数,然后附加目录名和文件名。以下是完整的程序。请记下我在程序中所做的命令。
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv) {
if(2 != argc)
{
printf("Directory name missing!\n");
return 0;
}
DIR *dp = NULL;
struct dirent *dptr = NULL;
FILE *input_file;
FILE *next_file;
char c,cwd[256]; //created new character array
if (NULL == (dp = opendir(argv[1])))
{
printf("Cannot open the given directory %s", argv[1]);
exit(1);
}
else
{
while((dptr = readdir(dp))!=NULL)
{
if(!strcmp (dptr->d_name, "."))
{
continue;
}
if(!strcmp (dptr->d_name, ".."))
{
continue;
}
if(getcwd(cwd, sizeof(cwd)) == NULL) //this is important
{
printf("No such file or directory");
continue;
}
if(dptr->d_name[0]=='.') //Files never begin with '.'
continue;
strcat(cwd,"/"); //For windows "\"
strcat(cwd,argv[1]);
strcat(cwd,"/"); //For windows "\"
strcat(cwd,dptr->d_name);
printf("%s",cwd); //check for working directory
input_file = fopen(cwd, "r");
printf("%s\n",dptr->d_name); //validation check
if(input_file == NULL)
{
perror("Cannot open file or no file exists\n");
fclose(input_file);
return 0;
}
c = fgetc(input_file);
while(c != EOF)
{
printf("%d", c);
}
printf("%s\n", dptr->d_name);
}
closedir(dp);
}
return 0;
}