I am trying to write a basic file reading/editing program and can't seem to figure out what's wrong with my fopen code. I think it has something to do with fgets or my if ( (fopen....) == NULL) line because I get the stderr every time. When I force the path it works but when the filename is entered by the user it goes to stderr. Here it is:
Code:
void read_file(void)
{
char display_buf[BUFSIZE];
char filename_buf[FBUF];
char *filename;
getchar();
puts("Enter name of text file to display.");
fgets(filename_buf, FBUF, stdin);
filename = (char *)malloc(strlen(filename_buf));
if (filename == NULL)
{
fprintf(stderr, "Memory allocation error");
exit (1);
}
strcpy(filename, filename_buf);
printf("%s", filename);
//getchar();
if ( (fp = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Error opening file.");
exit(1);
}