复制文件时出现分段错误

segmentation fault while copying a file

本文关键字:分段 错误 文件 复制      更新时间:2023-10-16

我有以下简单的代码,但是当我在Unix上使用GCC编译和运行时,我遇到了分段错误。是因为文件命名或将一个文件复制到其他文件。任何帮助表示赞赏..

#include <iostream>
#include <stdio.h>
using namespace std;
void copy(char *infile, char *outfile) {
    FILE *ifp; /* file pointer for the input file */
    FILE *ofp; /* file pointer for the output file */
    int c; /* character read */
    /* open i n f i l e for reading */
    ifp = fopen (infile , "r" );
    /* open out f i l e for writing */
    ofp = fopen(outfile, "w");
    /* copy */
    while ( (c = fgetc(ifp)) != EOF) /* read a character */
        fputc (c, ofp); /* write a character */
    /* close the files */
    fclose(ifp);
    fclose(ofp);
}
main() 
{
copy("A.txt","B.txt");
}

您发布的代码是正确的

 ifp = fopen (infile , "r" );  //will return NULL if file not there 
 while ( (c = fgetc(ifp)) != EOF)     

在使用时,如果您当前目录中没有 A.txt 文件,则可能会出现分段错误。

如果 A.txt 不存在,ifp 的值将为 NULL (0)。 然后,此函数调用将出现段错误。

fgetc(ifp)

因此,更改代码以检查文件打开(每个文件)上的 NULL,例如:

ifp = fopen (infile , "r" );
if (ifp == NULL) {
    printf("Could not open %sn", infile);
    exit(-2);
}

您可能还必须在文件顶部添加此包含:

#include <stdlib.h>

在参数中使用copy(const char* infile, const char* outfile)以避免不必要的警告。

此外,您的文件可能不在执行代码的当前目录中。因此,请提供文件的完整路径