简体   繁体   中英

C - replace string in file using char pointer

I realize there are tons of answers about this, but I didn't find any answer that does it like I want.

I want to edit the IPADDR parameter in the linux ifcfg-eth0 file in order to change the IP address.

I have code which finds the line that starts with "IPADDR", and I have a pointer to the start of the line.

I am not sure how to edit this line in the file.

Here is the code:

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??

    }
}

thnaks!

Files don't act like text editor buffers. You can't expect to do editor-type operations (replacing a line, editing a line) on files.

The only exception is if your new line is exactly the same length as the old one, then you can operate in binary mode on the file and do a write over just the right number of bytes.

In general you can't, and the right way is to load it all into memory, edit there, then write it all out, effectively overwriting the old file with a new one with the desired contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM