Capture Results from System()?

Apr 8, 2008 at 7:54pm
Hello,
I am trying to write a basic program that searches a user's hard drive for PST files. Once the program finds the files, I would like to be able to use that data to copy the files to another location.

So far, my program can find the files I am looking for...but I have not been able to figure out how to capture the information from the system so that I can setup a copy command? Does anyone have any thoughts or suggestions? Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
 
    //PROGRAM TITLE & COLOR
    system("title SearchPST By: maximusava");
    system("color 9B");
    
    
    //VARIABLES
    string findPST = "dir c:\\ /s /b | find \".pst\"";
    string s;
      
    cout << "\nSearching for .PST files...\n\n";
    
    string command = findPST;
    system( command.c_str() ); 
    
/*
 AT THIS POINT I WOULD LIKE TO TAKE THE OUTPUT FROM THE SYSTEM AND 
 USE IT TO WRITE A COMMAND - SO THAT I CAN COPY THE FILES TO A DESIRED LOCATION 
*/    
    system("PAUSE");
    return EXIT_SUCCESS;
}
Apr 9, 2008 at 10:37am
One method is to redirect the output of the command into some file and process that file. So your code will look something like this...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.
.
.

//VARIABLES
    string findPST = "dir c:\\ /s /b | find \".pst\" > tmp.txt";
    string s;
      
    cout << "\nSearching for .PST files...\n\n";
    
    string command = findPST;
    system( command.c_str() ); 

    /* Here write some code to process the list of pst files from tmp.txt */

.
.
.


Apr 10, 2008 at 4:20pm
Thank you msram...that does work. Now I'm trying to figure out how to take this information and putr it into variables so I can copy specific files. Unfortunatly, I do not have the most extensive C++ background. If you have any suggestions, I'll gladly take them...otherwise - Google, here I come! Thanks again!
Apr 10, 2008 at 7:23pm
Well if you include fstream.h, then you could use getline like this to get each file path as a line:

1
2
3
4
5
6
7
8
9
10
11
12
fstream Stream;
string path;
Stream.open(tmp.txt); //open the file
if(!Stream.isopen()) {
     cerr << "Error: tmp.txt not found!";
     //do other error related stuff
} else {
     while(!Stream.eof()) {
          getline(Stream, path); //get one line of the file into 'path'
          //use the path to access the file/move/copy it
     }
}


Or, if you want to get all the paths at once, I would suggest using a vector of strings like this:

1
2
3
4
5
6
vector <string> paths;
while(!Stream.eof()) {
     getline(Stream, path);
     paths.push_back(path);
}
//look through vector for paths and do stuff 
Last edited on Apr 10, 2008 at 7:34pm
Topic archived. No new replies allowed.