Search code examples
c++linuxsystem

how can I pass a parameter to the system function with quotes?


I'm trying to reduce columns of top funcion and save it into a file but I don't know how do it using system() function with quotes. I'm doing it like this:

system("top -b n1 | grep \"^ \" | awk '{ printf(\"%s %s %s %s %s %s %s\n\", $1, $2, $8, $3, $9, $10, $12); }' >> file

I'm pretty sure the problem is with the quotes, can someone help me?


Solution

  • The problem is not with your quotes. First, you are missing a closing "), and I'm not sure how you are trying to use the variable file but it looks like you are mixing up strings with variables. Make sure that the variable file is indeed used as a variable when you add it to your command string. Lastly, you are escaping \n wrong which messes up your output. You should escape that backslash, so you need to type \\n to wind up with \n in your awk command.

    This should work:

    string file = "test.txt"; 
    system((string("top -b n1 | grep \"^ \" | awk '{ printf(\"%s  %s  %s  %s  %s  %s  %s\\n\", $1, $2, $8, $3, $9, $10, $12); }' >> ") + file).c_str());