思路:打开目标文件,读取文件内容到缓存区,找到修改的字符串,把缓存区内容重新写入文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
if(argc != 2){
printf("Input error!!!\n");
exit(-1);
}
int fd_open;
int file_size;
char *read_buff;
char *address;
fd_open = open(argv[1],O_RDWR);
if(fd_open == -1){
printf("open error!1\n");
}
file_size = lseek(fd_open,0,SEEK_END);
lseek(fd_open,0,SEEK_SET);
read_buff = (char *)malloc(file_size);
read(fd_open,read_buff,file_size);
address = strstr(read_buff,"DEV=");
if(address == NULL){
printf("not found!!\n");
}
address = address+strlen("DEV=");
*address = '8';
lseek(fd_open,0,SEEK_SET);
write(fd_open,read_buff,file_size+2);
close(fd_open);
return 0;
}
修改后: