0

How do I create a new file based on the command line.

For example if my argv[1] is file.extension I want to create a new text file named file.txt.

I tried this:

ofstream a;
a.open("argv[1].txt");

But it very obviously creates a file called argv[1].txt instead of file.txt

1 Answers1

1
a.open( (std::string(argv[1]) + ".txt").c_str() ); // if parameter is file with no extension

or

a.open( argv[1] ); // if parameter is file with extension

Possibly:

std::string file = argv[1];
// do whatever you want (change extension, as commented)
a.open( file.c_str() );

But I agree this question should probably be deleted....don't think it will help anyone else....

jpo38
  • 20,821
  • 10
  • 70
  • 151
  • The file already has an extension, I want to remove that extension and replace it with .txt – Mr Identical Oct 03 '15 at 15:57
  • Then, just use google with "c++ change file extension" and you'll magically find http://stackoverflow.com/questions/6417817/easy-way-to-remove-extension-from-a-filename – jpo38 Oct 03 '15 at 15:58
  • I get this error : no matching function for call to ‘std::basic_fstream >::open(std::string&)’ – Mr Identical Oct 03 '15 at 16:08
  • Edited the post, it takes a `const char*`: use `.c_str()` to get it from the `std::string` – jpo38 Oct 03 '15 at 16:10
  • Thanks for the help, although it doesn't create a new file at all for some reason. And how do I change the extension to .txt from .extension – Mr Identical Oct 03 '15 at 16:15
  • So do you actually just want `rename`? http://en.cppreference.com/w/cpp/io/c/rename – TheUndeadFish Oct 03 '15 at 16:20
  • What if I want to prepend something to the filename? currently I get a.txt as the output. I want to get my_a.txt as the output now. I tried it using a + but got an error: invalid operands of types ‘const char [3]’ and ‘const char*’ to binary ‘operator+ – Mr Identical Oct 03 '15 at 16:35
  • This just opens the file, ext step is to write into it....please pickup a tutorial and follow it.... – jpo38 Oct 03 '15 at 16:50