复制文件时出现分段错误
segmentation fault while copying a file
我有以下简单的代码,但是当我在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)
以避免不必要的警告。
此外,您的文件可能不在执行代码的当前目录中。因此,请提供文件的完整路径。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?