我遇到了一个问题,即使用C语言中的命令行参数将内容从一个文件复制到另一个文件。具体如下:
问:编写一个C程序,使用C语言中的命令行参数将一个文件的内容复制到另一个文件。应该获得以下输出:
1) >>> ./a.out
Display: "Insufficient arguments"
2) >>> ./a.out a.txt b.txt
Display: File not created
3) >>> ./a.out a.txt b.txt
Display: File is empty
4) >>> ./a.out a.txt b.txt
Display: File successfully copied
5) >>> b.txt
Display: Hello World.
我为上述问题编写的代码是:
#include<stdio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
FILE *fp1,*fp2;
char ch;
if(argc!=3)
{
printf("\n insufficient arguments.\n");
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"w");
if(fp1==NULL || fp2==NULL)
{
printf("\n File not created.\n");
exit(0);
}
if (NULL != fp1)
{
fseek (fp1, 0, SEEK_END);
int size = ftell(fp1);
if (0 == size)
{
printf("File is empty.\n");
exit(0);
}
}
while(!feof(fp1))
{
ch=fgetc(fp1);
fputc(ch,fp2);
}
printf("\n File successfully copied ");
fclose(fp1);
fclose(fp2);
}
当我运行上面的代码时,我得到输出:
sh-4.2$ gcc main.c
sh-4.2$ ./a.out
Insufficient arguments.
sh-4.2$ gcc main.c
sh-4.2$ ./a.out a.txt b.txt
File not created.
sh-4.2$ gcc main.c
sh-4.2$ ./a.out a.txt b.txt // I created one empty file a.txt
File is empty.
sh-4.2$ gcc main.c
sh-4.2$ ./a.out a.txt b.txt // Saved "Hello World" to a.txt and created empty file b.txt
File successfully copied
sh-4.2$ gcc main.c
sh-4.2$ b.txt // Why can't I carry out this operation as given in question?
sh: ./b.txt: Permission denied
sh-4.2$ gcc main.c
sh-4.2$ cat b.txt
�
sh-4.2$ cat a.txt
Hello World
我有这个符号:�当我试图显示b.txt的内容时。但是当我显示a.txt的内容时,我得到了Hello World。我无法通过简单地输入问题中给出的名称来显示b.txt的内容。它只是在我包括“猫”之后才出现的。命令在文件名之前。
我想以最简单的方式解决问题。我错过了代码中的任何逻辑或任何一行吗?