我想使用C ++读取和设置/ etc / network / interfaces中的所有参数。
这是我的interfaces文件
# /etc/network/interfaces
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.1.6
network 192.168.1.0
netmask 255.255.255.0
broadcast 192.168.1.255
gateway 192.168.1.1
hwaddress ether 50:76:A6:04:00:01
auto eth0:0
iface eth0:0 inet static
address 100.100.100.251
netmask 255.255.255.0
无论如何更容易吗?
答案 0 :(得分:2)
你在这里..
#include <iostream>
using std::cout;
using std::endl;
#include <fstream>
using std::ifstream;
#include <cstring>
const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
const char* const DELIMITER = " ";
int main()
{
// create a file-reading object
ifstream fin;
fin.open("/etc/network/interfaces"); // open a file
if (!fin.good())
return 1; // exit if file not found
// read each line of the file
while (!fin.eof())
{
// read an entire line into memory
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
// parse the line into blank-delimited tokens
int n = 0; // a for-loop index
// array to store memory addresses of the tokens in buf
const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0
// parse the line
token[0] = strtok(buf, DELIMITER); // first token
if (token[0]) // zero if line is blank
{
for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
{
token[n] = strtok(0, DELIMITER); // subsequent tokens
if (!token[n])
break; // no more tokens
}
}
// process (print) the tokens
for (int i = 0; i < n; i++) // n = #of tokens
{
if (strcmp (token[i],"\taddress") == 0 )
cout << "IP: " << token[i+1] << endl;
else if (strcmp (token[i],"\tnetwork") == 0 )
cout << "NET: " << token[i+1] << endl;
else if (strcmp (token[i],"\tnetmask") == 0 )
cout << "MASK: " << token[i+1] << endl;
else if (strcmp (token[i],"\tbroadcast") == 0 )
cout << "BCAST: " << token[i+1] << endl;
else if (strcmp (token[i],"\tgateway") == 0 )
cout << "GTW: " << token[i+1] << endl;
else if (strcmp (token[i],"\thwaddress") == 0 )
cout << "MAC: " << token[i+2] << endl;
}
cout << endl;
}
}