1

I have the following code, but when I run it, the output is printed instead of being copied to the text file.

void checkText()
{
    ifstream my_file("test.txt");
    if (my_file.good()) {
        cout << "File exist" ;
    }
    else {
        ofstream outputFile;
        outputFile.open("test.txt");
        outputFile << system("head -n 1024 words.txt");
        outputFile.close();
        cout << "Done!\n";
    }
}

How do I print the system command to my text file?

Jeugasce
  • 197
  • 1
  • 3
  • 11
  • Possible duplicate of [How to execute a command and get output of command within C++ using POSIX?](http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix) – Logman Apr 05 '17 at 15:58

2 Answers2

1

system returns an int and not the "output" from the command that is executed.

One way to do this would be to redirect the command to the file you want:

    std::system("head -n 1024 words.txt > test.txt");
crashmstr
  • 28,043
  • 9
  • 61
  • 79
0

you can also use for printing the output in a text file freopen(); command

freopen("input file name.txt", "r", stdin);
freopen("output file name.txt", "w", stdout);