-1

Can you help me? I am truna to create a program with supporting cmd->int main(int argc, char *argv[]). Using class, I want to create a method for writting my infromation. The name of the .txt file is third argument.

My problem is that I need to open() my file, but the name of the file can be changed. I tried to open the specified file it's 1.txt. But How should I do so in order to give the name of the file in cmd because my method, which is in Header, see that name?

My method in header:

void recordData()
{
    wRecord.open("1.txt", std::ios_base::app);//the hard way to create a file in this method. 

    int i=0;
        wRecord  << "Name of your city: " << Name << std::endl;
        ......................................................
        wRecord  << "Quanity of schools in your city: " << Schools << std::endl;
        wRecord  << std::endl;
}

But it should be wRecord.open(argv[3], std::ios_base::app); ,I think. But how correctly give argv[3]?

My code ,when I call void recordData():

if (argv[1] == create)
    {
        wRecord.open(argv[3], std::ios_base::app);// here is I put any name of file
     //But I can't use any name because in method there is only `1.txt`
        if (!wRecord)
        {
            std::cerr << "Error: canNOT oprn a text file" << std::endl;
            exit(-1);
        }
    }
Nikita Gusev
  • 143
  • 10
  • Have you tried passing argv[3] to open() ? What happened? have you tried DEBUGGING your program? – roalz Feb 24 '17 at 10:45
  • not sure what you mean, but you can pass `argv[3]` to your function as `char* fileName` or what do you need? – xander Feb 24 '17 at 10:49
  • @roalz Yes, I've tried to passing `argv[3`] to `open() `. It created a file with name which named in my method (`1.txt`). But if i give another name as a argument (for example: `2.txt`). It does nothing. – Nikita Gusev Feb 24 '17 at 10:51
  • 1
    `recordData(char *filename) { wRecord.open(filename, ...) }` That is, pass filename received in `argv[3]` to `recordData(argv[3]);` – sameerkn Feb 24 '17 at 10:51
  • @xander yes, how do I need to pass `argv[3]` in my fuction. Can you show me that,please? – Nikita Gusev Feb 24 '17 at 10:52
  • @Nikita please provide a Minimal, Complete, and Verifiable example (http://stackoverflow.com/help/mcve) that we can look at and compile, otherwise it will be hard to help you. – roalz Feb 24 '17 at 10:54
  • @roalz he gave me some advice (`sameerkn`) , that was I needed – Nikita Gusev Feb 24 '17 at 10:56
  • Possible duplicate of [Read file line by line](http://stackoverflow.com/questions/7868936/read-file-line-by-line) – Lord_Curdin Feb 24 '17 at 12:25

1 Answers1

0

You should add a char* parameter to your recordData() function, in order to pass it from main() argv[] to wRecord.open().

I.e.:

void recordData(char *filename) 
{ 
    wRecord.open(filename, std::ios_base::app);
    ...
}
roalz
  • 2,699
  • 3
  • 25
  • 42