#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc,char **argv)
{
FILE *from_fd;
FILE *to_fd;
long file_len=0;
char buffer[BUFFER_SIZE];
char *ptr;
char ch_test;
if(argc!=3)
{
printf("(Usage:%s fromfile tofile)\n",argv[0]);
exit(1);
}
//open file
if ((from_fd=fopen(argv[1],"rb"))==NULL)
{
/* code */
printf("open %s Error\n",argv[1] );
exit(1);
}
if ((from_fd=fopen(argv[2],"wb"))==NULL)
{
/* code */
printf("open %s Error\n",argv[2] );
exit(1);
}
//get file size
fseek(from_fd,0L,SEEK_END);
file_len=ftell(from_fd);
fseek(from_fd,0L,SEEK_SET);
printf("from file size is=%d\n",file_len);
while(!feof(from_fd))
//while((ch_test=fgec(from_fd))!=EOF)
{
fread(buffer,BUFFER_SIZE,1,from_fd);
if(BUFFER_SIZE>=file_len)
{
fwrite(buffer,file_len,1,to_fd);
}
else
{
fwrite(buffer,BUFFER_SIZE,1,to_fd);
file_len=file_len - BUFFER_SIZE;
}
bzero(buffer,BUFFER_SIZE);
}
fclose(from_fd);
fclose(to_fd);
exit(0);
}
程序名:file_cp.c
file1:abcde
file2:null
file_cp file1 file2(将file1的内容复制到file2中)
我的问题是,我的代码总是在while(!feof(from_fd))这个语句块内循环退不出来(gdb调试)
而且总是说file1的大小为0
请教大仙们,为什么会这样?
------解决方案--------------------
//if ((from_fd=fopen(argv[2],"wb"))==NULL)
//改成:
if ((to_fd=fopen(argv[2],"wb"))==NULL)
{
/* code */
printf("open %s Error\n",argv[2] );
exit(1);
}