Bootstrap

C语言文件基础:模拟copy命令,将一个文本文件复制到另一个文本文件

完整题目:

编程模拟DOS或linux下的复制文件命令copy,将一个文本文件(源文件)复制到另一个文本文件(目标文件)中。命令行格式为:
命令名     源文件名    目标文件名
假设本题程序编译连接后的可执行文件名为fcopy,则下面命令将scr.txt复制到scr.bak中
fcopy     src.txt     scr.bak

解法:

1.利用fgetc和fputc函数

#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.文件重定向

#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函数和fputs函数

#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函数和fprintf函数

#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;
}
;