|
To achieve a simple cp command in Linux. This is the "APUE" where the fourth chapter of a exercises.
In fact, the idea is very simple, to clarify the rules on the line. Rule 1: The source file have to exist, otherwise an error; Rule 2: If the destination file exists is created, if there is, you are prompted whether to overwrite, it is covered, not just a re-build.
Code is given below:
/ * Simple cp command * /
#include < stdio.h>
#include < stdlib.h>
#include < string.h>
int my_cp (char * argv []);
int main (int argc, char * argv []) / * argv [1] and argv [2] is the path to the file * /
{
my_cp (argv);
return 0;
}
int my_cp (char * argv []) / * passed in the path of the file * /
{
FILE * fp1, * fp2;
char ch;
char flag; / * prompt whether to overwrite * /
char filename [256];
if ((fp1 = fopen (argv [1], "r")) == NULL) / * source file have to exist, otherwise an error * /
{
printf ( "error: the% s does not exist.", argv [1]);
exit (1);
}
if ((fp2 = fopen (argv [2], "r"))! = NULL) / * 2 If the file already exists * /
{
printf ( "The file% s has been exist, cover Y / N:?", argv [2]);
scanf ( "% c", & flag);
fclose (fp2); / * Here because if either or else, have to re-open the file, so here is first switched off * /
if (flag == 'y' || flag == 'Y') / * 2 to overwrite the file * /
{
if ((fp2 = fopen (argv [2], "w")) == NULL)
{
printf ( "Can not rewrite!");
exit (1);
}
while ((ch = fgetc (fp1))! = EOF) / * Copy the contents of the file to the file 1 * 2 /
fputc (ch, fp2);
}
else / * 2 does not overwrite the file, create a new file 2 * /
{
/ * File named 2 filename (1) * /
strcpy (filename, argv [2]);
strcat (filename, "-copy");
if ((fp2 = fopen (filename, "a")) == NULL)
{
printf ( "Can not build the file% s.", filename);
exit (1);
}
while ((ch = fgetc (fp1))! = EOF) / * Copy the contents of the file to the file 1 * 2 /
fputc (ch, fp2);
}
}
else / * 2 file does not exist, create * /
{
// Fclose (fp2); / * should not be the phrase, because the front with r mode is on, if it does not exist, it will return a NULL pointer, fclose (NULL) to be wrong * /
if ((fp2 = fopen (argv [2], "w")) == NULL)
{
printf ( "Can not rewrite!");
exit (1);
}
while ((ch = fgetc (fp1))! = EOF) / * Copy the contents of the file to the file 1 * 2 /
fputc (ch, fp2);
}
fclose (fp1);
fclose (fp2);
}
When the destination file already exists, you are prompted to overwrite:
When the destination file does not exist, create it:
Shortcomings:
1. Only one copy support, not support copy-many, this could be improved.
2. Because it is a simple copy command, and there is no argument to support. |
|
|
|