I have the below code (not mine) trying to get it to work out of curiousity. from here C low-level standard-in to accept filename then printing file contents to stdout
int checkfile(void)
{
char buffer[4096];
char userInput[100];
int input_file1;
int n;
/* Check file existence. */
printf("Enter the filename: \n");
fflush(NULL);
if (!fgets(userInput,sizeof(userInput),stdin))
{
perror("fgets");
exit(EXIT_FAILURE); };
if((input_file1 = open(userInput, O_RDONLY)) < 0)
{
perror(userInput);
exit(1);
}
while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
if((write(STDOUT_FILENO, buffer, n)) < 0)
{
perror("failed to display file to output");
close(input_file1);
exit(1);
}
}
}
whenever i run the code and try to open a file called "success.txt" i get a segmentation fault
"RUN FINISHED; Segmentation fault; core dumped; real time: 3s; user: 0ms; system: 0ms"
i'm also calling this from my main code as
checkfile();
if that makes any difference.
Could someone point out to me what i'm missing because i can't see it at the moment. i have a feeling some of my variables are not set properly...but unsure thank you.