【发布时间】:2014-09-18 11:17:29
【问题描述】:
我正在尝试使用“C”将数据从一个文件复制到 UNIX 中的另一个文件。复制过程中的条件是 1) 源文件不退出 2) 源文件存在但目标文件不存在。 3) 如果源文件和目标文件都存在,则选择覆盖目标文件或将源文件数据附加到目标文件数据。
以下代码在前两种情况下运行良好。但不适用于最后一种情况(覆盖和附加)。当我执行程序并输入现有的源文件时,目标文件位置选择程序表示数据已被附加但实际上数据没有附加或覆盖的选项之一。
请告诉我如何使程序在最后一种情况下正常工作。
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#define BUFFSIZE 512
#define PERM 0644
int main (int argc, char *argv[])
{
char buffer[BUFFSIZE];
int infile;
int outfile;
int choice;
size_t size;
if((infile = open(argv[1], O_RDONLY,0)) < 0)
{
printf("Source file does not exist\n");
return -1;
}
if((outfile=open(argv[2],O_WRONLY,PERM))>0)
{
// printf("Destination Fiel Exists , Do you wish to Overwrite or Appened destination file Data : \n Enter 1 to overwrite or ,\n 0 to Append \n");
scanf("%d",&choice);
if(choice==1)
{
if((outfile=open(argv[2],O_WRONLY|O_CREAT |O_EXCL, PERM))>=0)
{
printf("Destination file data is overwriten by source file data \n");
return -2;
}
}// end if (choice =1)
else
{
if(choice==0)
{
if((outfile=open(argv[2],O_WRONLY |O_CREAT |O_APPEND, PERM ))>=0)
{
printf("Destination file data is appended with source file data : \n");
}
} // end if(choice==0)
else
{
printf("Entered invalid choice.: \n");
}
return -3;
}
}
else
{
if((outfile=open(argv[2],O_WRONLY | O_CREAT | O_EXCL,PERM))<0)
{
printf("Enter the desitination file along with source file \n");
return -4;
}
else {
printf(" Data has been copied to \t%s\n", argv[2]);
}
}
while ((size=read(infile, buffer, BUFFSIZE)) > 0)
{
write(outfile, buffer, size);
}
close(infile);
close(outfile);
return 0;
}
【问题讨论】: