Sharat Chandra
Sharat Chandra

Reputation: 4544

how to used c++ variable inside system ( ) function

I have a .txt file containing 2 columns . I have to search for a pattern in the first column and delete that line from the file that matches .

I have to do this inside a c++ program.

What are the options I could use ?

I though of using a system() function and call sed (which seems efficient). But I'm not sure how to use sed inside system (). The search pattern is a c++ variable and I'm not sure how to insert it inside sed

int pattern;
.
.
.

system ("sed -i '/pattern/d' file.txt");

I know it could take this form, but I appreciate any help from you, about how to use c++ variable as a search pattern inside sed

Upvotes: 0

Views: 3258

Answers (2)

Dave Rager
Dave Rager

Reputation: 8150

std::string s = "sed -i '/" + pattern + "/d' file.txt";

system(s.c_str());

Upvotes: 0

John
John

Reputation: 2326

assemble in a std::string and then use c_str(). You might find ostringstream (from sstream header) useful for assembling the string.

Upvotes: 3

Related Questions