1

I am trying to let the user to save with a custom name but it doesn't seem to work, When I hard code it, it is fine and works but not the other way around.

char name[100];
    printf("\nEnter File name to save the file: ");
    fgets(name, 100, stdin);
    FILE *fLocation = fopen(name, "a+");//I can just put the complete path and name and it works
    if (fLocation == NULL){
        printf("Error, could't create the file\n");
        return;
    }
travis
  • 11
  • 2
  • fgets also add a trailing newline, you could remove it with `name[strcspn(name, "\n")] = 0;` after the fgets call, see also this fine answer: https://stackoverflow.com/a/28462221 (additional hint: you need to add a #include for strcspn) – Stephan Schlecht Mar 18 '20 at 19:52

1 Answers1

0

you also can use snprintf to open or make a user named file

int main()
{
    char name[100];
    char buf[BUFSIZ];
    printf("\nEnter File name to save the file: ");
    scanf("%s", name);
    snprintf(buf, sizeof(buf), "%s.txt", name);//for text file add .txt to entered name
    FILE* fLocation = fopen(buf, "a+");
    if (fLocation == NULL)
    {
        printf("Error, could't create the file\n");
        return 0;
    }
}
hanie
  • 1,863
  • 3
  • 9
  • 19