私は現在、システムプログラミングを学んでおり、CでLinuxのcpコマンドを実装しています。この実装は私の理解ではあるが、ファイルを同じディレクトリにコピーし、カレントディレクトリのディレクトリにファイルをコピーします。複数のファイルをディレクトリにコピーするLinux cpコマンドの実装
複数のファイルを同時にディレクトリにコピーできるようにするには、このコードを変更することができます(つまり、 "copy f1.txt f2.txt f3.txt/dirInCurrentDir") またはさらに "copy d1/d2/d3/f1 d4/d5/d6/f2 d ")、2つのファイルをディレクトリdにコピーします。私は変更がmain()で発生しなければならないことを知っていますが、if-elseステートメントにどのように追加できますか?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFERSIZE 1024
#define COPYMORE 0644
void oops(char *, char *);
int copyFiles(char *src, char *dest);
int dostat(char *filename);
int mode_isReg(struct stat info);
int main(int ac, char *av[])
{
/* checks args */
if(ac != 3)
{
fprintf(stderr, "usage: %s source destination\n", *av);
exit(1);
}
char *src = av[1];
char *dest = av[2];
if(src[0] != '/' && dest[0] != '/')//cp1 file1.txt file2.txt
{
copyFiles(src, dest);
}
else if(src[0] != '/' && dest[0] == '/')//cp1 file1.txt /dir
{
int i;
for(i=1; i<=strlen(dest); i++)
{
dest[(i-1)] = dest[i];
}
strcat(dest, "/");
strcat(dest, src);
copyFiles(src, dest);
}
else
{
fprintf(stderr, "usage: cp1 source destination\n");
exit(1);
}
}
int dostat(char *filename)
{
struct stat fileInfo;
//printf("Next File %s\n", filename);
if(stat(filename, &fileInfo) >=0)
if(S_ISREG(fileInfo.st_mode))
return 1;
else return 0;
return;
}
int copyFiles(char *source, char *destination)
{
int in_fd, out_fd, n_chars;
char buf[BUFFERSIZE];
/* open files */
if((in_fd=open(source, O_RDONLY)) == -1)
{
oops("Cannot open ", source);
}
if((out_fd=creat(destination, COPYMORE)) == -1)
{
oops("Cannot create ", destination);
}
/* copy files */
while((n_chars = read(in_fd, buf, BUFFERSIZE)) > 0)
{
if(write(out_fd, buf, n_chars) != n_chars)
{
oops("Write error to ", destination);
}
if(n_chars == -1)
{
oops("Read error from ", source);
}
}
/* close files */
if(close(in_fd) == -1 || close(out_fd) == -1)
{
oops("Error closing files", "");
}
return 1;
}
void oops(char *s1, char *s2)
{
fprintf(stderr, "Error: %s ", s1);
perror(s2);
exit(1);
}
私はこれでelse if文を置き換えました。あるファイルの内容を別のファイルにコピーしている場合や、ファイルをdirInCurrentDirectoryにコピーしている場合に動作します。私のファイルをdirにコピーするには、これを行う必要があります(./cp2 f1.txt d/f1.txt)。そうでなければ、まだ複数のファイルをディレクトリにコピーすることはできません。ここで私のループ 'else if(src [0]!= '/' && dest [0] == '/') { \t int i; (i = 1; i = strlen(src); i ++){ \t av [ac-2] = av [ac-1]; \t; \t} \t strcat(dest、 "/"); \t strcat(dest、av [i]); \t copyFile(av [i]、av [ac-1]); } ' – Kim94