I'm trying to figure out how user input can be used as a filename in C. Here's the simple program I wrote.
#include <stdio.h>
#define MAX 100
int main()
{
FILE *fp;
char name[MAX];
printf("Enter filename: ");
fgets(name, MAX, stdin);
if((fp = fopen(name, "w")) == 0)
printf("File cannot be opened!");
return 0;
}
It always prints "File cannot be opened".
fgets retains the newline in the input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With