[求助]拜托帮帮忙~C语言实现Copy

sbinayu 2004-12-27 04:07:14
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp_in;
FILE *fp_out;
if(argc!=3)
{
printf("You forgot to enter a file name\n");
return 0;
}
if((fp_in = fopen(argv[1], "r"))==NULL)
{
printf("Can't open infile.");
return 0;
}
if((fp_out = fopen(argv[2], "w"))==NULL)
{
printf("Can't open outfile.");
return 0;
}
while (!feof(fp_in))fputc(fgetc(fp_in),fp_out);
fclose(fp_in);
fclose(fp_out);
return EXIT_SUCCESS;
}

1.此程序copy是没有问题…不过copy出来的文件里都会多一个乱码文字???
是不是!feof那一行有错误?拜托高手帮帮忙…

2.请问要如何将以下程序码加入以上的源码里?(检查文件关闭是否错误?)
ex:
if(fclose(fp_in) == EOF)
{
printf("文件关闭错误");
return 0;
}
if(fclose(fp_out) == EOF)
{
printf("文件关闭错误");
return 0;
}

3.没有使用ferror()函式检查读取过程是否发生错误。这该如何加入到以上源码中呢?
if(ferror(fp_in))
{
printf("文件读取错误");
return 0;
}
拜托高手帮帮忙…感激…
...全文
165 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
herryhuang 2004-12-27
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <fcntl.h>

#define BUFSIZE 8192

int main(int argc, char* argv[])
{
int n;
char buf[BUFSIZE];
int fd1, fd2;

if(argc < 3)
{
printf("Usage: %s <filename1> <filename2>\n", argv[0]);
return(-1);
}

if((fd1 = open(argv[1], O_RDONLY)) < 0)
{
printf("File open error on %s.\n", argv[1]);
return(-2);
}

if((fd2 = open(argv[2], O_WRONLY | O_CREAT)) < 0)
{
printf("File open error on %s.\n", argv[2]);
return(-3);
}

while(( n = read(fd1, buf, BUFSIZE)) > 0)
if(write(fd2, buf, n) != n)
{
printf("write error.\n");
close(fd1);
close(fd2);
return(-4);
}

if(n < 0)
{
printf("read error.\n");
close(fd1);
close(fd2);
return(-5);
}

close(fd1);
close(fd2);
return(0);
}

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧