Question

What is the C/C++ command for creating a file in a certain directory with the name of a certain variable read from the keyboard ? For example: a text file with the name John previously read from the keyboard, the program will create the file John.txt

Was it helpful?

Solution

Just do something like this, in this example I ask for the filename using the keyboard, then I create the file using fopen and passing it to filename written by the user.

#include <stdio.h>
#include <string.h>

int main(){
   FILE *f;
   char filename[40], path[255];
   strcpy(path,"folder/path/"); //copies the folder path into the variable

   printf("Insert your filename\n");
   scanf("%s",&filename);

   strcpy(path,filename);
   f = fopen(path,'w'); //w is for writing permission   

   //Your operations
   fclose(f);
   return 0;
}

Here is another example using POO which is better for C++:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
  string path = "my path";
  string filename;

  cout << "Insert your filename" << endl;
  cin >> filename;
  path = path + filename;

  ofstream f; 
  f.open (path.c_str()); //Here is your created file

  //Your operations
  f.close();
  return 0;
}

P.D: This example uses Unix's paths.

OTHER TIPS

C way: FILE* f = fopen(filename,"w"); (assuming that you want to write to it, else the second argument is "r".)

C++ way: std::fstream f(filename,std::ios::out); (assuming that you want to write, for reading it's std::ios::in)

Also, try to search C/C++ documentation before asking such questions. Check out this site next time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top