1

can the fopen() name your own file? For example

printf("Enter the name of the file you want to create");
scanf("%s", &name);

Then I want the scanned name to be the name of the file I want to create. Is there any way to do this? I know that you can just

fp = fopen("name of file.txt","w or a")

but what if the user asks for the name of the file itself?

  • You mean something like this: http://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c ? – Stefan Falk May 24 '15 at 10:09
  • 2
    Or do you mean "can I write `fp = fopen(name,"w")` to use the name of the file supplied by the user?" If so, the answer is "yes". – Simon May 24 '15 at 10:11
  • @simon, how will you convert it into a txt file then? the only thing hat it shows is the name and without its extension – llawliet_78 May 24 '15 at 10:15
  • 1
    @llawliet_78 , `fopen` with `w` as the second argument creates a `.txt` file with the specified name. [@pmg's answer](http://stackoverflow.com/a/30422328/3049655) shows how to do it. – Spikatrix May 24 '15 at 10:19
  • Generally, the user would be expected to supply the full filename, with path and extension. If you want to save the user the effort of providing all that information, the program would have to add them to the file name -- look up `strcat()` or the more sophisticated specialised functions listed at http://stackoverflow.com/questions/8900980/standard-or-free-posix-path-manipulation-c-library. – Simon May 24 '15 at 10:22

1 Answers1

3

Use the variable as an argument to fopen()

fgets(name, sizeof name, stdin);
name[strlen(name) - 1] = 0; // remove ENTER from name
fp = fopen(name, "w");
// error checking ommited for brevity

If you want to add a ".txt" extension to the input, use strcat() for example

fgets(name, sizeof name - 4, stdin); // save space for extension (thanks Cool Guy)
name[strlen(name) - 1] = 0; // remove ENTER from name
strcat(name, ".txt"); // add extension
fp = fopen(name, "w");
// error checking ommited for brevity
pmg
  • 106,608
  • 13
  • 126
  • 198
  • I usually use `sprintf` after an `fgets` to build the filename for the file, because it allows me to format it a little bit. For example, If I have files with a name like `Expedient_123456.txt`, I can ask the user for a number and then build the filename like `Expedient_%d.txt`. – Alexander George May 24 '15 at 10:49