my overall program creates a new file based on a file name and mode that the user enters, then checks to see if the file exists. Following that it outputs whether file creation was successful. It should be simple, but when I compile and build (successfully) with Geany and run, I get the following error in the terminal window (but only after entering the mode "r+"):
./geany_run_script.sh: line 5: 7395 Segmentation fault (core dumped) "./test" c
------------------
(program exited with code: 139)
Press return to continue
Then I ran it with gdb, after reading this
segmentation fault (core dump)
and got this error:
Program received signal SIGSEGV, Segmentation fault.
_IO_new_fclose (fp=0x0) at iofclose.c:54
54 iofclose.c: No such file or directory.
Here is my code:
#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;
}
The gdb error comes up after I enter the filename, unlike with Geany where I get the error after I enter mode "r+".
Please help, and simply ask if you need additional data. Thanks in advance.
Edit: I updated the code, and the bit about when I get the error. For some reason, it is now at a different point in the program depending on whether I run it with gdb or with Geany.
")
– user253751 Jan 03 '15 at 05:11