Linux implements simple cp commands
Implement simple cp commands in Linux. This is one of the exercises in Chapter 4 of APUE.
In fact, the idea is very simple. Just find out the rules. Rule 1: The source file must exist; otherwise, an error occurs. Rule 2: If the target file does not exist, it is created. If yes, it indicates whether to overwrite the file. If not, it is overwritten. If not, a new file is created.
The following code is provided:
/* Implement simple cp commands */
# 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] are file paths */
{
My_cp (argv );
Return 0;
}
Int my_cp (char * argv [])/* path of the uploaded file */
{
FILE * fp1, * fp2;
Char ch;
Char flag;/* Indicates whether to overwrite */
Char filename [256];
If (fp1 = fopen (argv [1], "r") = NULL)/* The source file must exist; otherwise, an error occurs */
{
Printf ("error: the % s doesn't exist.", argv [1]);
Exit (1 );
}
If (fp2 = fopen (argv [2], "r "))! = NULL)/* If file 2 already exists */
{
Printf ("The file % s has been exist, cover? Y/N: ", argv [2]);
Scanf ("% c", & flag );
Fclose (fp2);/* because the files need to be re-opened in both if and else, close the file first */
If (flag = 'y' | flag = 'y')/* overwrite file 2 */
{
If (fp2 = fopen (argv [2], "w") = NULL)
{
Printf ("Cannot rewrite! ");
Exit (1 );
}
While (ch = fgetc (fp1 ))! = EOF)/* copy the content of file 1 to file 2 */
Fputc (ch, fp2 );
}
Else/* Do Not Overwrite file 2, create a new file 2 */
{
/* Name file 2 is filename (1 )*/
Strcpy (filename, argv [2]);
Strcat (filename, "-copy ");
If (fp2 = fopen (filename, "a") = NULL)
{
Printf ("Cannot build the file % s.", filename );
Exit (1 );
}
While (ch = fgetc (fp1 ))! = EOF)/* copy the content of file 1 to file 2 */
Fputc (ch, fp2 );
}
}
Else/* If file 2 does not exist, create */
{
// Fclose (fp2);/* this statement is not required because it is opened in r mode. If it does not exist, the NULL pointer is returned. fclose (NULL) will cause an error */
If (fp2 = fopen (argv [2], "w") = NULL)
{
Printf ("Cannot rewrite! ");
Exit (1 );
}
While (ch = fgetc (fp1 ))! = EOF)/* copy the content of file 1 to file 2 */
Fputc (ch, fp2 );
}
Fclose (fp1 );
Fclose (fp2 );
}
If the target file exists, the system prompts whether to overwrite the file:
If the target file does not exist, create:
Disadvantages:
1. Only one-to-one replication is supported, and one-to-multiple replication is not supported. This can be improved.
2. Because it is a simple Copy command, no parameters are supported.
APUE exercise 4.6 source code ---- implement your own simple cp command
This article permanently updates the link address: