【发布时间】:2015-10-28 12:40:40
【问题描述】:
我知道有很多关于这个的答案,但我没有找到任何我想要的答案。
我想编辑 linux ifcfg-eth0 文件中的 IPADDR 参数以更改 IP 地址。
我有找到以“IPADDR”开头的行的代码,并且我有一个指向行首的指针。
我不确定如何编辑文件中的这一行。
代码如下:
FILE *fp;
char *line=NULL;
size_t len=0;
ssize_t read;
char subword[7];
// path to file
const char filename[]="/etc/sysconfig/..."
fp=fopen(filename, "w");
while((read = getline(&line, &len, fp)) != -1) {
memcpy(subword, &line[0], 6);
subword[6]='\0';
if(strcnp("IPADDR", subword) == 0)
{
// here I have a pointer to the line (variable "line") I want to replace
// the line looks like this "IPADDR=xxx.xxx.xxx.xxx"
// what to do here??? how to replace the ip??
}
}
谢谢!
【问题讨论】:
-
创建一个新文件,替换原始文件中的行,然后将其余部分替换掉。采用点分四进制表示法的 IP 地址并不总是每个字段 3 位。
-
为什么是 C?最好选择一个可能调用
sed的shell 脚本。如何做到这一点的一个例子在这里:unix.stackexchange.com/q/66878/10947