Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

command to file

Status
Not open for further replies.

charIie

Programmer
Feb 14, 2006
21
US
Hello, I'm working on a small project which would be taking the output of system command and putting them in a user given file. My first attemp I was using fstream for writing to the file. All it was writing was an integer dealing with the success of they system command. After researching Google, I found something that may work. Using popen I believe it is possible. I guess this isn't standard c++ code, so if anyone could elaborate on that or possibly give me an alternative to look into it would be greatly appriciated. So far all the attempts that I have tried with the popen did not work.

Thanks in advance,
charIie
 
Here is an example from some of my code:
Code:
std::ofstream OFile; // stream set up
OFile.open("MyFile.txt");  // name of file open for overwritting
// OFile.open("MyFile.txt", std::ios::app); // Same file for appending

if (!OFile) // Something went wrong
{
    // do something
    cerr << "Could not open MyFile.txt" << std:endl; // for example
}
else // File ready for input
{
    OFile << "Stick something in file" << std::endl;
    OFile << "Variable << I+1 << " OF " << SamplesStr << std::flush; // or you can use variables
}

//Done
OFile.close();

See if that helps.

James P. Cottingham
-----------------------------------------
[sup]I'm number 1,229!
I'm number 1,229![/sup]
 
Ah, yes I have tried a similar code, but it would only write an integer to the file. I need it to be able to take a system() call such as ping 127.0.0.1 and write that output to a file. As far as I know it can't be done normally with the fstreams. If I'm wrong let me know, Thanks
 
Yes, you can. You can write strings, integers, floats, etc. to a stream, including file streams. As a matter of fact, you can overload the operators to use any custom type you want.

If you only want to output a system call, why not use the redirection (> or >>) command? For example: ping 127.0.0.1 > MyFile.txt to overwrite/create a file or ping 127.0.0.1 >> MyFile.txt to append a file.

James P. Cottingham
-----------------------------------------
[sup]I'm number 1,229!
I'm number 1,229![/sup]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top