Anyone knows how to open a text file and write the content of it to a text file with command line or arguments, i mean using the argc and argv.

thanx for answer!

Recommended Answers

All 2 Replies

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(int argc,char* argv[])
string input;
if(argc<2){
cout<<"Enter a command line argument!!"<<endl;
return 1;
}
ofstream fout("new.txt");
cout<<"Enter some text to the file..";
cin>>input;
fout<<input;
fout.close;
ifstream fin("new.txt");
if(!fin.is_open()){
cout<<"Unable to open file!!"<<endl;
return 1;
}
return 0;
}

The executable of this code can only work if some command-line arguments are added.
Hope this helped!!(Pls, you would show your appreciation by adding to my reputation)

int main(int argc, char*argv[])
{
   ofstream out;
   if( argc == 2)
   {
      out.open(argv[1]);
       if( !out.is_open())
       {
           cout << "Failed to open the file \"" << argv[1] << "\"\n";
           return 1;
       }
   {
   else
   {
        cout << "usage: myprog filename\n";
        return 1`;
   }
   // now write to the file
  ...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.