我正在将源文件source.txt
复制到另一个文件destination.txt
。在运行代码之前,这两个 .txt 文件都存在于目录中。每个文件只包含一个句子。但我在终端输出中看到error: Segmentation fault
。这是C代码:
#include<stdio.h>
#include<stdlib.h>
int main(void) {
FILE* sptr = NULL;
FILE* dptr = NULL;
int ch = 0;
if((sptr = fopen("source.txt", "r")) == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if((sptr = fopen("destination.txt", "w")) == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
答案 0 :(得分:2)
看起来你已经堕落了复制粘贴itis!
if((sptr = fopen("source.txt", "r")) == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if((sptr = fopen("destination.txt", "w")) == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
重复 sptr
,因此该文件仅供写入。试图从中读取可能会导致分段错误。
另外,为什么要使变量初始化变得复杂?这可以写成:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE* sptr = fopen("source.txt", "r");
FILE* dptr = fopen("destination.txt", "w");
int ch = 0;
if(sptr == NULL) {
printf("Error in opening source file.\n");
exit(1);
}
if(dptr == NULL) {
printf("Error in opening destination file.\n");
exit(1);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
答案 1 :(得分:2)
您正在写入目标文件,如
fputc(ch,dptr);
请注意,执行上面的行时,dptr为空。
因此分割错误。
答案 2 :(得分:1)
以下代码:
FILE*
变量EXIT_FAILURE
stdlib.h
宏
醇>
现在,代码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE* sptr = NULL;
FILE* dptr = NULL;
int ch = 0;
if((sptr = fopen("source.txt", "r")) == NULL)
{
perror("fopen to read source.txt failed");
exit( EXIT_FAILURE );
}
if((dptr = fopen("destination.txt", "w")) == NULL)
{
perror("fopen to trucante/write destination.txt failed");
exit( EXIT_FAILURE);
}
while((ch = fgetc(sptr)) != EOF)
fputc(ch, dptr);
fclose(sptr);
fclose(dptr);
return 0;
}
初始条件:
source.txt包含:
this is a sentence
destination.txt包含:
this will be overwritten
运行程序后:
source.txt包含:
this is a sentence
destination.txt包含:
this is a sentence