Full title:
Programmatically simulate the copy file command copy under DOS or linux, copy a text file (source file) to another text file (target file). The command line format is:
command name source file name target file name
Assuming that the executable file name after the program is compiled and connected is fcopy, the following command will copy scr.txt to
scr.bak fcopy src.txt scr.bak
solution:
1. Use fgetc and fputc functions
#include<stdio.h>
int fcopy(char *,char *);
int main(int argc,char *argv[])
{
int i;
if (argc < 3) {
printf("The command syntax is incorrect.fcopy [source filename] [target filename]\n");
exit(0);
}
if (fcopy(argv[1], argv[2]) == 0)
printf("No such a file:%s or %s\n",argv[1],argv[2]);
return 0;
}
int fcopy(char*sourcename, char*targetname)
{
char c;
FILE* fp1, * fp2;
if (!(fp1 = fopen(sourcename, "r")))return 0;
if (!(fp2 = fopen(targetname, "w")))return 0;
while ((c = fgetc(fp1)) != EOF)fputc(c,fp2);
fclose(fp1);
fclose(fp2);
return 1;
}
2. File redirection
#include<stdio.h>
int fcopy(char *,char *);
int main(int argc,char *argv[])
{
int i;
if (argc < 3) {
printf("The command syntax is incorrect.fcopy [source filename] [target filename]\n");
exit(0);
}
if (fcopy(argv[1], argv[2]) == 0)
printf("No such a file:%s or %s\n",argv[1],argv[2]);
return 0;
}
int fcopy(char*sourcename, char*targetname)
{
char c;
if (freopen(sourcename, "r", stdin) == NULL)return 0;
if (freopen(targetname, "w", stdout) == NULL)return 0;
while ((c = getchar()) != EOF)putchar(c);
return 1;
}
3.fgets function and fputs function
#include<stdio.h>
int fcopy(char*, char*);
int main(int argc, char* argv[])
{
int i;
if (argc < 3) {
printf("The command syntax is incorrect.fcopy [source filename] [target filename]\n");
exit(0);
}
if (fcopy(argv[1], argv[2]) == 0)
printf("No such a file:%s or %s\n", argv[1], argv[2]);
return 0;
}
int fcopy(char* sourcename, char* targetname)
{
char a[81];
FILE* fp1, * fp2;
if (!(fp1 = fopen(sourcename, "r")))return 0;
if (!(fp2 = fopen(targetname, "w")))return 0;
while (fgets(a,80,fp1)!=NULL)fputs(a,fp2);
fclose(fp1);
fclose(fp2);
return 1;
}
4.fscanf function and fprintf function
#include<stdio.h>
int fcopy(char*, char*);
int main(int argc, char* argv[])
{
int i;
if (argc < 3) {
printf("The command syntax is incorrect.fcopy [source filename] [target filename]\n");
exit(0);
}
if (fcopy(argv[1], argv[2]) == 0)
printf("No such a file:%s or %s\n", argv[1], argv[2]);
return 0;
}
int fcopy(char* sourcename, char* targetname)
{
char c;
FILE* fp1, * fp2;
if (!(fp1 = fopen(sourcename, "r")))return 0;
if (!(fp2 = fopen(targetname, "w")))return 0;
while (fscanf(fp1,"%c",&c)!=EOF)fprintf(fp2,"%c",c);
fclose(fp1);
fclose(fp2);
return 1;
}