我会将代码精简到只有我遇到问题的部分。
当我执行以下操作时,代码有效
int main() {
FILE * fptr1 = fopen("in.txt", "r");
fread(data, sizeof(char), size, fptr1);
.
.
.
FILE * fptr2 = fopen("out.txt", "w");
fwrite(data, sizeof(char), size, fptr2);
fclose(fptr2);
}
但是,当我使用 fgets 或 scanf 获取输入和输出文件名时,出现段错误。
int main() {
char inputfile[100];
char outputfile[100];
printf("name of input file: \n");
fgets(inputfile, 100, stdin);
printf("name of output file: \n");
fgets(outputfile, 100, stdin);
.
.
.
}
我已经研究了一段时间了。我尝试使用 scanf 并尝试更改输入文件和输出文件的分配大小,但我不断收到:
Segmentation fault (core dumped)
最佳答案
使用 fgets()
,生成的文件名 inputfile
和 outputfile
包含终止换行符。它导致以下 fopen()
失败并返回 NULL
。
但是,在调用 fread()
或 fwrite()
之前,您没有检查 FILE*
的无效性,这导致段错误。
关于c - 为什么在使用用户输入获取文件名时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243416/