我正在写信,使用 C 语言将文本从一个文件复制到 UNIX 中的另一个文件。下面是我的代码的一部分。当我执行程序时,我收到段错误错误。
任何帮助表示赞赏..
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main (int argc, char *argv[])
{
char buffer[BUFFSIZE];
int infile;
int outfile;
int n;
size_t size;
printf("Enter the Source file name: \n");
scanf("%s",&argv[1]);
printf("Enter the Destination file name : \n");
scanf("%s", &argv[2]);
if((infile = open(argv[1], O_RDONLY,0)) < 0)
{
perror("Source file does not exist");
return -1;
}
if((outfile=open(argv[2],O_WRONLY,0644))>0)
{
printf("Target/Destination File Exists:\n \n ");
//printf("Target Fiel Exists , Do you wish to Overwrite or Appened Data to it: \n \n 1=Yes(Overwrite),\n 0=No(Append):\n");
scanf("%d",&n);
if(n==1)
{
if((outfile=open(argv[2],O_WRONLY|O_CREAT |O_EXCL, 0644)>=0))
{
printf("File is Being opened in Overwrite Mode: \n \n");//File is overwrited
}
}
}
}
最佳答案
将数据读入 argv
数组是非常非常不寻常的。您可能不应该考虑这样做。
即使您真的想这样做,以下内容仍然是错误的:
scanf("%s",&argv[1]);
argcv 的元素是指向字符串的指针,因此函数调用会将字符串读入存储指针的内存中。 argv[1]
元素将无效,并且输入的字符串很可能会溢出并丢弃该后的一个或多个元素。
尝试如下:
char infile_name[81];
char outfile_name[81];
printf("Enter the Source file name: \n");
scanf("%80s", infile_name);
printf("Enter the Destination file name : \n");
scanf("%80s", outfile_name);
并将其余引用调整为 argv[1]
和 argv[2]
。
关于c - unix 下文件复制时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25904007/