这是cp的一个原始实现,我在Linux机器(Ubuntu)上编译并运行了它,这段代码适用于任意大小的文本文件,但对于pdfs或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;
}
发布于 2016-12-14 12:59:39
我用EOF的方式错了吗?
这是错误的。EOF
是int
型的。fgetc
的返回值也是int
类型。将值存储在char
中。
如果文件包含值为-1
/255
的任何字节,则代码将失败。当然,文本文件不会,但是大型二进制文件很可能包含这样的字节。
将mychar
类型更改为int
将解决此问题。
另一个错误是NUL
-terminate char_buff
时可能存在缓冲区溢出。如果文件的偶数为256个,那么当您添加i
-terminator并在缓冲区外写入时,NUL
将是-terminator。
https://stackoverflow.com/questions/41141808
复制相似问题