这是 cp 的原始实现,我在 Linux 机器(Ubuntu)上编译并运行它,此代码适用于任何大小的文本文件,但不适用于 pdf 或 mp3,我不知道我错了什么。我使用EOF的方式有问题吗?它编译并运行没有错误,但不适用于所有类型的文件。
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define MAX_SIZE 2
#define MAX_BUF_SIZE 256
int main(int argc, char* argv[])
{
FILE *pFile_src=NULL;
FILE *pFile_dest=NULL;
char* mychar;
char *SRC, *DEST;
int i=0,j;
char char_buff[MAX_BUF_SIZE];
mychar= (char *)malloc(sizeof(char *));
if(argv[1]!=NULL)
SRC=argv[1];
else
printf("\nUSAGE: ./Ex_ManualCP_prog src_file dest_file.\nFirst arg should be a filename, cannot be empty.\n");
if(argv[2]!=NULL)
DEST=argv[2];
else
printf("\nSecond arg should be a filename, cannot be empty.\n");
mychar= (char *)malloc(MAX_SIZE*sizeof(char *));
//initialize text buffer
for(j=0;j<MAX_BUF_SIZE;j++)
char_buff[j]='\0';
pFile_src=fopen(SRC,"r"); //Open file to read and store in a character buffer
pFile_dest=fopen(DEST,"w"); //open destination file
if(pFile_dest==NULL)
printf("\nFile specified as Destination DOES NOT EXIST.\n");
if(pFile_src==NULL)
printf("\nFile specified as Source, DOES NOT EXIST.\n");
else
{
//printf("\n----File opened successfully-----\n");
while(((*mychar=fgetc(pFile_src))!=EOF))
{
if(i>=MAX_BUF_SIZE)
{
i=0;
}
char_buff[i]=*mychar;
fputc(char_buff[i],pFile_dest); //write buffer data into opened file
++i;
}
char_buff[i]='\0';
fclose(pFile_src); //close source file
}
fclose(pFile_dest);
if(pFile_src!=NULL && pFile_dest!=NULL)
printf("\n\n-----Copy Done!----\n-----Reached end of file.-----\n");
return 0;
}
最佳答案
Is it wrong the way i use EOF?
这是错误的。 EOF
的类型为 int
。 fgetc
的返回值也是int
类型。您将值存储在 char
中。
如果文件包含任何值为 -1
/255
的字节,您的代码将会失败。当然,文本文件不会,但大型二进制文件可能包含此类字节。
将 mychar
的类型更改为 int
将解决该问题。
另一个错误是当您使用 NUL
终止 char_buff
时可能会出现缓冲区溢出。如果文件是 256 的偶数倍,则 i
将是
256
当您添加 NUL
终止符时,您将在缓冲区之外写入。
关于cp的C实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141808/