文章目录
1.修改配置文件的思路
- 先找到要修改哪个配置文件
- 打开要修改的配置文件
- 将配置文件中所有的内容都读取到缓存区(buf)中
- 利用strstr()函数,找到具体要修改的字符串,然后修改字符串对应的数据
- 将修改后的数据,再写到配置文件中
strstr()比较函数介绍
#include <string.h>
char *strstr(const char *haystack, const char *needle);
const char *haystack: 被查的目标 (str1)
const char *needle: 被查的对象 (str2)
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;
如果str2不是str1的子串,则返回NULL。
本地的配置文件:TEST.config
2.配置文件的修改
使用strstr来寻找“LENG=”,查找到光标在该字符串的首位置,然后让指针往前移动该字符串长度的位置,修改该字符串。
示例代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char **argv){
int fdSrc;
char *readbuf = NULL;
if(argc != 2){
printf("fixue error\n");
exit(-1);
}
fdSrc = open(argv[1],O_RDWR);
int size = lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
readbuf = (char *)malloc(sizeof(char)*size + 5);
int n_read = read(fdSrc,readbuf,size);
lseek(fdSrc,0,SEEK_SET);
// close(fdSrc);
// fdSrc = open(argv[1],O_RDWR|O_TRUNC);
char *p = strstr(readbuf,"LENG=");
if(p == NULL){
printf("not fount\n");
exit(-1);
}
p = p + strlen("LENG=");
*p ='5';
int n_write = write(fdSrc,readbuf,n_read);
close(fdSrc);
return 0;
}