I've searched through google and this forum to see if I found what I need before make a new post but I couldn't find anything related to my needs.
I have some sort of text based configuration file for a server application which has the following format:
1 2
server-address = 127.0.0.1
server-port = 2500
What I need is to read the value after the = sign of each line and save that value into a variable, but I can't figure out how to do that. This is the code so far:
bool bReadConfigFile()
{
std::ifstream configFile;
std::string line;
char cAddress[16};
int iPort = 0;
configFile.open("Login.cfg", std::ios::in);
if (configFile.is_open())
{
while (std::getline(configFile, line))
{
if (memcmp(line.c_str(), "server-address", 14) == 0)
{
// I need to get the value and copy it into
// cAddress[16].
}
elseif (memcmp(line.c_str(), "server-port", 11) == 0)
{
// Same as before but with iPort.
}
}
configFile.close();
}
else
{
WriteLog("Configuration file was not found!", DEF_MSG_ERROR);
returnfalse;
}
returntrue;
}
If you guys can at least give me a clue about how to achieve this I will be very grateful.
#include <iostream>
#include <string>
#include <fstream>
int main(int argc, char *arg[]) {
std::ifstream ReadFile("file.txt");
if(!ReadFile.is_open()) {
std::cerr << "Error: Could not open file.\n";
return -1;
}
std::string word;
while(ReadFile >> word) {
if(word == "server-address") {
ReadFile.ignore(3);
ReadFile >> word;
// std::cout << word << '\n';
// store
}
elseif(word == "server-port") {
ReadFile.ignore(3);
ReadFile >> word;
// std::cout << word << '\n';
// store
}
}
ReadFile.close();
return 0;
}
I took a different approach by reading the first word on the line and then comparing it before performing any other operations. I then ignored the two spaces and the equals sign by calling the member function ignore (reference link below). After that, I stored the next string of characters into the string object "word." The only thing you need to do is store the strings that were read from the file. Does my answer satisfy you?