I want to do something similar to sed -i 's/abc/def/' file
but without temp file. In my case match and replacement are of same length; is the following safe:
fd = open(file, O_RDWR);
fstat(fd, &sbuf);
mm = mmap(0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
i = 0;
while (i < sbuf.st_size) {
memcpy(tmpbuf, mm + i, BUFSIZ); // read from mem to tmpbuf (BUFSIZ at a time)
if ((p = strstr(tmpbuf, needle))) { // match found
memcpy(mm + i + (p - tmpbuf), replace, strlen(replace)); // strlen(replace) == strlen(needle)
}
i += BUFSIZ;
}
munmap(mm, sbuf.st_size);
fsync(fd);
close(fd);
(err handling omitted for brevity)
Also, not sure if mmap
is making this any faster!