c - unix 下文件复制时出现段错误

标签 c unix segmentation-fault file-handling

我正在写信,使用 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/

相关文章:

c - 为什么“while(!feof(file))”总是错误的?

linux - 是否有这样的命令可以在 shell 中合并多个文件?

c - 调用 FreeImage_GetPixelColor() 时出现奇怪的段错误

c - 我正在编写这段代码来分配一些内存并返回指针,但我收到段错误错误

c - 通过插入空字符在C中分割字符串

c - 提高屏幕捕获性能

c - 围绕结构数组中的函数指针的讨论。什么是好的做法?

c - 在C语言中,如何将数组传递给函数?

unix - 如何在 Bourne Shell 中重复一个字符?

linux - 执行此 'mv' 命令后我的文件发生了什么?