General TC > Programming & Scripting - Unofficial
How to define a variable compatible with npos in C++
Rich:
Hi Paul_123
I did decide to test this for myself by adding lst=onboot.lst to the end of cmdline.
Result:
eloc was set to 4294967295
work was set to 4294967226
onbootName was correctly set to onboot.lst and no seg fault occurred.
Since a trailing space or end of string marker (\0) are both
acceptable in this case, it works correctly because C++
hid the error (or failed gracefully).
Thank you for the explanation.
Paul_123:
Was playing with Copilot in github today.
Prompt: write code in c++ to parse the linux kernel command line
--- Code: ---#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
int main() {
const std::string cmdlinePath = "/proc/cmdline";
std::ifstream cmdlineFile(cmdlinePath);
if (!cmdlineFile.is_open()) {
std::cerr << "Error: Could not open " << cmdlinePath << std::endl;
return 1;
}
std::string cmdline;
std::getline(cmdlineFile, cmdline);
cmdlineFile.close();
std::map<std::string, std::string> cmdlineParams;
std::istringstream stream(cmdline);
std::string token;
while (std::getline(stream, token, ' ')) {
size_t equalPos = token.find('=');
if (equalPos != std::string::npos) {
std::string key = token.substr(0, equalPos);
std::string value = token.substr(equalPos + 1);
cmdlineParams[key] = value;
} else {
cmdlineParams[token] = ""; // Parameter without a value
}
}
// Display the parsed parameters
std::cout << "Parsed Kernel Command Line Parameters:" << std::endl;
for (const auto& param : cmdlineParams) {
std::cout << param.first << " = " << (param.second.empty() ? "(no value)" : param.second) << std::endl;
}
return 0;
}
--- End code ---
Not drastically different than what we are doing. Copilot always used size_t for the result coming from find.
Navigation
[0] Message Index
[*] Previous page
Go to full version