c - C:当我想打开和写入文件时,如何解决“分段错误”?
问题描述
我正在尝试打开一个文件,但我既没有将“r”切换为“rt”,也没有将“at+”切换为“fp”总是返回 NULL。在我输入一个字符串后,输出将是一个分段错误。我犯的错误在哪里?请帮帮我
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp;
char str[120] = {0}, strTemp[100];
if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
printf("Cannot open file\n");
}
printf("Input a string:");
gets(strTemp);
strcat(str, "\n");
strcat(str, strTemp);
fputs(str, fp);
fclose(fp);
return 0;
}
预期输出:
Input a string: hello
实际输出:
Cannot open file
Input a string: hello
Segmentation fault: 11
解决方案
代替
if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
printf("Cannot open file\n");
}
经过
if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
printf("Cannot open file\n");
return 0;
}
否则你将在 in 之后使用空指针fputs(str, fp);
正如 Jabberwocky 所说,gets很危险,因为你可以溢出缓冲区,使用fgets更安全
当然你也可以在一个else
分支中做你的工作:
#include <stdio.h>
#include <string.h>
int main(){
FILE *fp;
char str[120] = {0}, strTemp[100];
if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
printf("Cannot open file\n");
}
else {
printf("Input a string:");
fgets(strTemp, sizeof(strTemp), stdin);
strcat(str, "\n");
strcat(str, strTemp);
fputs(str, fp);
fclose(fp);
}
return 0;
}
推荐阅读
- vba - 确认两个表达式是否引用同一个 MS Word 表
- regex - 值两侧的测量单位的正则表达式 (200 g/g 200)
- asp.net - 注销时的 Clear-Site-Data 标头仅从缓存中清除已注销的页面
- algorithm - 在列表上多次映射时间复杂度
- python - 如何在VS代码中切换到Anaconda环境而不将Anaconda添加到系统PATH
- angular - 模板方法中的换行符?
- r - 用开头的模式替换字符串末尾的模式
- kubernetes - 用于微调初始启动 pod 计数的 Kubernetes HPA 属性
- python - 在python的一个类中重复使用上下文管理器
- python - 从 C 扩展模块中看不到方法