Home > Software design >  Create a *.txt File That is Named After the Input of a User [duplicate]
Create a *.txt File That is Named After the Input of a User [duplicate]

Time:10-08

Example being like..

fPointer = fopen("%s.txt", "r");

I know this does not work however I was just curious if there was anything similar to this idea? I also would need to create the file too.

CodePudding user response:

int main(void) {
  char word[100];
  char fileName[100];
  printf("Enter a word: ");
  scanf("%s", word);
  sprintf(fileName, "%s.txt", word);
  fopen(fileName, "w");
  return 0;
}

Try it online here.

CodePudding user response:

You can juste use scanf to take user input and create filename with that.

#include <stdio.h>

int main()
{
    char filename[100] = "";
    
    printf("Enter file name : ");
    scanf("%[^\n]", filename);
    strcat(filename, ".txt");
    
    FILE * userfile = fopen(filename, "w ");

    return 0;
}

Of course ideally you should check user input first to ensure there's no forbidden character in it.

  •  Tags:  
  • c
  • Related