user1631862
user1631862

Reputation:

Reading line from text file into C++ system() command

I'm new to C++, and I'm trying to read a string from a text file that only contains one string and use that as input for a system() call. Here's what I have:

#include <iostream>
#include <string>
#include <fstream>

int main(int argc, const char * argv[])
{
    std::string curlString = "/usr/bin/curl -O ";
    std::ifstream file("/Users/test/Desktop/test.txt");
    if (file) {
    std::string line;
    while (std::getline( file, line ));
    system(curlString + line);
    }
 }

This is probably a complete and utter mess, so thanks so much for helping out, I really appreciate it.

Thanks in advance for any insight!

Upvotes: 0

Views: 665

Answers (2)

ChaosCakeCoder
ChaosCakeCoder

Reputation: 367

I am not sure what the problem really is. Is it the reading from the file? There are planty of example how to do this in stackoverflow. Why do you not do something like:

std::string curlString = "/usr/bin/curl -O ";
std::string urlString= /* function that reads one line of code and does some verifcation if it is a URL */
system(curlString + urlString);

Upvotes: 1

nneonneo
nneonneo

Reputation: 179552

That seems like an awfully roundabout way to achieve your result.

There are a few easier ways to achieve this:

  • you could build the string entirely in C++ by prompting the user there
  • you could pass the string from Bash to C++ by sending it in as a command line argument in argv
  • you could just call curl from bash

A file here just seems like overkill unless you have a specific need to create a file.

Upvotes: 0

Related Questions