我有一个文件夹,其中有多个文件夹,每个文件夹包含许多照片,例如,我有一个文件夹2018
,文件夹2018
包含11
个更多文件夹,所有这11个文件夹包含一定数量的图像,所有图像都具有相同的格式.jpg。我想将来自不同文件夹的所有图像复制到一个文件夹中。
我尝试过以下代码:
#include<stdio.h>
#include<stdio.h>
#include<dirent.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
#define MAX 1024
int main()
{
char arSrcPath[] = "/home/mpe4/Src"; /*Source directory path*/
char arDestPath[] = "/home/mpe4/Dest"; /*dest directory path*/
struct dirent* spnDirPtr; /* struct dirent to store all files*/
DIR* pnOpenDir = NULL; /*DIR Pointer to open Dir*/
DIR* pnReadDir = NULL; /*DIR POinter to read directory*/
pnOpenDir = opendir(arSrcPath);
if(!pnOpenDir)
printf("\n ERROR! Directory can not be open");
else
{
int nErrNo = 0;
while(spnDirPtr = readdir(pnOpenDir))
{
if(nErrNo == 0)
nErrNo = errno;
printf("\n Now writing %s file...",spnDirPtr->d_name);
printf("\n dest file name = %s/%s\n", arDestPath, spnDirPtr->d_name);
struct stat st_buf;
stat(spnDirPtr->d_name, &st_buf);
if (S_ISDIR (st_buf.st_mode))
{
continue;
}
else if (S_ISREG (st_buf.st_mode))
{
FILE* pnReadFile = fopen(spnDirPtr->d_name,"r");
if(pnReadFile)
{
printf("\n Now reading %s file...",spnDirPtr->d_name);
char strDestFileName[MAX] = {0};
sprintf(strDestFileName, "%s/%s", arDestPath, spnDirPtr->d_name);
printf("\n dest file name = %s\n", strDestFileName);
FILE* pnWriteFile = fopen(strDestFileName, "w"); /*File Pointer to write in file*/
if(pnWriteFile)
{
char buffer[MAX] = {0}; /*Buffer to store files content*/
while(fgets(buffer, MAX, pnReadFile))
{
fputs(buffer, pnWriteFile);
}
fclose(pnWriteFile);
}
else
{
printf("\n Unable to open file %s", strDestFileName);
}
fclose(pnReadFile);
}
else
{
printf ("\nERROR! File Could not be open for reading");
}
}
}
if(nErrNo != errno)
printf ("\nERROR Occurred!\n");
else
printf ("\nProcess Completed\n");
}
closedir(pnOpenDir);
return 0;
}
但是这段代码只是复制文件而不是文件中的数据。