我的整个程序根据用户输入的文件名和模式创建一个新文件,然后检查该文件是否存在。然后输出文件创建是否成功。它应该很简单,但是当我使用Geany编译和构建(成功)并运行时,我在终端窗口中收到以下错误(但只有在进入模式" r +"后):
./geany_run_script.sh: line 5: 7395 Segmentation fault (core dumped) "./test" c
------------------
(program exited with code: 139)
Press return to continue
然后我在阅读了这个
之后用gdb运行它segmentation fault (core dump)
并收到此错误:
Program received signal SIGSEGV, Segmentation fault.
_IO_new_fclose (fp=0x0) at iofclose.c:54
54 iofclose.c: No such file or directory.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
char filename[100];
char mode[2];
int main(int argc, char **argv)
{
printf("Enter filename:\n>");
scanf("%s", &*filename);
printf("Select a mode from the list:\nr reading\nw writing\na append\nr+ reading & writing (at beginning, overwriting)\nw+ reading & writing (overwrite on existing)\na+ reading & appending (new data appended at end of file)\n>");
scanf("%s", &*mode);
FILE * fp;
fp = fopen(filename, mode);
if (fp == NULL)
{
printf("Failed to open\n");
}
else
{
printf("Succesfully opened\n");
}
fclose(fp);
return 0;
}
输入文件名后出现gdb错误,与Geany不同,我输入模式后出现错误&#34; r +&#34;。
请提供帮助,只需询问您是否需要其他数据。提前谢谢。
编辑:我更新了代码,以及有关何时收到错误的信息。出于某种原因,它现在在程序中的不同点取决于我是使用gdb还是使用Geany运行它。
答案 0 :(得分:1)
文件模式需要超过2个字符:&#34; r +&#34;等(NUL终结者)。小心避免缓冲区溢出。
char mode[3];
fgets(mode, sizeof(mode), stdin);
fclose在非打开文件上的行为未定义。
if (fp == NULL) {
printf("Failed to open\n");
} else {
printf("Succesfully opened\n");
fclose(fp); /* only close if fp != NULL, and only close once */
}
所有在一起:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char filename[100];
char mode[3];
char *p;
printf("Enter filename:\n>");
fgets(filename, sizeof(filename), stdin);
if ((p = strchr(filename, '\n')) != NULL) {
*p = '\0'; /* remove any newline */
}
printf("Select a mode from the list:\n"
"r reading\n"
"w writing\n"
"a append\n"
"r+ reading & writing (at beginning, overwriting)\n"
"w+ reading & writing (overwrite on existing)\n"
"a+ reading & appending (new data appended at end of file)\n>");
fgets(mode, sizeof(mode), stdin);
if ((p = strchr(mode, '\n')) != NULL) {
*p = '\0';
}
printf("opening %s with mode %s.\n", filename, mode);
FILE *fp = fopen(filename, mode);
if (fp == NULL) {
printf("Failed to open\n");
} else {
printf("Succesfully opened\n");
fclose(fp);
}
return 0;
}