Reputation: 112
everybody. I'm having a rough time trying to code this thing, I hope you can give me some advice. I'm trying to retrieve some parameters from a text file and then append them to a variable char array and then execute that char array with a pipe, the command is a bash command.
My problem is how to access the file to retrieve the parameters, I've tried with buffers and string but conversions haven't really helped, here's the basic idea of my code.
Working code if I write the command directly to the code:
#include <string.h>
#include <cstdlib>
#include <cstdio>
char *out[10], line[256], command[] = {"mycommand parameter1 parameter2 ..."};
FILE *fpipe;
fpipe = (FILE*)popen(command,"r")
fgets(line, sizeof line, fpipe)
out[0] = strtok (line, "="); // <--- I'm tokenizing the output.
My approach to read from file:
std::ifstream file("/path/to/file", std::ifstream::in);
//std::filebuf * buffer = file.rdbuf();
char * line = new char[];
//buffer->sgetn (line, lenght);
getline(file, line)
The commented line are things I've tried, there were others but I didn't comment them.
I'm considering port it to C later, but first I want to get it going. And I haven't really implemented the append code since I can't read the file yet. Hope you can give me some tips, thanks!
Upvotes: 2
Views: 436
Reputation: 137
The std::getline()
takes istream
and string
as arguments.
istream& getline (istream& is, string& str);
Here is the documentation: http://www.cplusplus.com/reference/string/string/getline/
Upvotes: 1
Reputation: 31
I would advice to do something like :
#include <string>
#include <fstream>
std::istream file("/path/to/file"); //ifstream is only infile
std::string astringpar;
float afloatingpar;
//in this example there is a string and a float in the file
//separated by space, tab or newline
//you can continue/replace with int or other in fonction of the content
while (file >> astringpar >> afloatpar)
{
//here do what you want with the pars
}
ciao Ice
Upvotes: 0
Reputation: 96790
You're on the right track, you just need to use a std::string
which is what getline
receieves:
std::string line;
std::getline(file, line);
That reads the first line. But if you needed to read the entire contents of the file into line
just do:
std::string line;
std::istreambuf_iterator<char> beg = file.rdbuf();
std::istreambuf_iterator<char> end;
line.assign(beg, end);
Upvotes: 2