簡単なcpコマンドを実現
3539 ワード
#include
#include
#include
#include
#include
#include
#include
int copyAFileToAnother(char* oFile,char* tFile)
{
struct stat oFileStat;
int fileSize;
int oFileHandle,tFileHandle;
char* buffer;
stat(oFile,&oFileStat);
fileSize=oFileStat.st_size;
buffer = (char *)malloc(fileSize+1);
oFileHandle = open(oFile,O_RDONLY);
read(oFileHandle,buffer,fileSize);
tFileHandle = open(tFile,O_RDWR|O_CREAT,0644);
write(tFileHandle,buffer,fileSize);
close(tFileHandle);
free(buffer);
close(oFileHandle);
}
int copyFileToDirectory(char* file,char* directory)
{
int dirLen = strlen(directory);
int fileNameLen = strlen(file);
char* tFile;
if(directory[dirLen-1]!='/')
{
tFile = (char *)malloc(fileNameLen+dirLen+2);
strcpy(tFile,directory);
tFile[dirLen]='/';
strcpy(tFile+dirLen+1,file);
}else
{
tFile = (char *)malloc(fileNameLen+dirLen+1);
strcpy(tFile,directory);
strcpy(tFile+dirLen,file);
}
printf("%s
%s
",file,tFile);
copyAFileToAnother(file,tFile);
}
int main(int argc,char* argv[])
{
struct stat tFileStat;
stat(argv[2],&tFileStat);
if((tFileStat.st_mode&S_IFMT)==S_IFREG)
copyAFileToAnother(argv[1],argv[2]);
else if((tFileStat.st_mode&S_IFMT)==S_IFDIR)
copyFileToDirectory(argv[1],argv[2]);
else printf("This file can not be handled.
");
}
version2:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define NAME_MAX_LENGTH=100;
void getLastSlashElement(const char * path,char * element)
{
int len = strlen(path);
int headIndex=len-2,tailIndex=(path[len-1]=='/'?len-1:len);
while(headIndex>=0 && path[headIndex]!='/')
headIndex--;
headIndex++;
int index;
for(index=0;index+headIndexd_name,".")&&strcmp(dp->d_name,".."))
{
strcpy(newOName+oDirLen+1,dp->d_name);
printf("newOName:%s newTDir:%s
",newOName,newTDir);
recursiveDemo(newOName,newTDir);
}
free(newOName);
closedir(oFile);
free(newTDir);
free(simpleDirName);
}
}
void recursiveCopy(char* arg1,char* arg2)
{
struct stat tFileStat;
stat(arg2,&tFileStat);
if((tFileStat.st_mode&S_IFMT)!=S_IFDIR)
{
printf("The target must be a directory! exit
");
return;
}
recursiveDemo(arg1,arg2);
}
int main(int argc,char* argv[])
{
if(strcmp(argv[1],"-r")==0)
recursiveCopy(argv[2],argv[3]);
else
nonRecursiveCopy(argv[1],argv[2]);
}