I'm trying to write a function that receives a pointer to a file and two strings (a filename and a mode). It should ask for a filename, and open a file while error-checking. But the code doesn't compile and I've spent a couple of hours looking for a reason.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 41
char* s_gets(char *str, int len);
void openFilename(FILE* fp, char* fname, char* mode);
int main(void)
{
char fname[LEN];
FILE *fp = NULL;
int ch;
// This works
printf("Enter a filename: ");
s_gets(fname, LEN);
fp = fopen(fname, "r");
// This does not
// openFilename(fp, fname, "r");
while ((ch = getc(fp)) != EOF)
putchar(ch);
fclose(fp);
return 0;
}
char* s_gets(char *str, int len)
{
char* ret_val;
char* newline;
ret_val = fgets(str, len, stdin);
if (ret_val) {
newline = strchr(str, '\n');
if (newline)
*newline = '\0';
else
while (getchar() != '\n') continue;
}
return ret_val;
}
void openFilename(FILE *fp, char *fn, char *mode)
{
printf("Enter a filename: ");
s_gets(fn, LEN);
printf("Opening %s... ", fn); // This never runs!
if ((fp = fopen(fn, mode)) == NULL) {
fprintf(stderr, "Couldn't open %s. Quitting.\n", fn);
exit(EXIT_FAILURE);
}
}
The s_gets()
function works fine if I call it from main, but as soon as I call it from openFilename()
I get a Segmentation fault: 11
which usually has to do with arrays out of bounds, right? So I'm assuming that I'm not passing properly the string argument for the filename to openFilename()
, but how can I do that?