linux C语言 配置文件的修改
首先需要修改的原文件假如是TEST.txt
LENG=3
SDK=1
QWER=19
TEST.txt 内容如上
假如我要把TEST.txt里面的LENG=3修改为LENG=5,那么应该怎么做呢,代码如下
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
int fdSrc;
char *buf=NULL;
if(argc!=2)
{
printf("error\n");
exit(-1);
}
fdSrc=open(argv[1],O_RDWR);
int size=lseek(fdSrc,0,SEEK_END);
lseek(fdSrc,0,SEEK_SET);
buf=(char *)malloc(sizeof(char)*size+8);
read(fdSrc,buf,size);
char *p=strstr(buf,"LENG=");
p=p+strlen("LENG=");
*p='5';
lseek(fdSrc,0,SEEK_SET);
write(fdSrc,buf,strlen(buf));
close(fdSrc);
return 0;
}
编译成功之后,运行./a.out TEST.txt 就可以把LENG=3修改为LENG=5。
char *strstr(const char *haystack, const char *needle);
strstr为字符查找函数,haystack就是总的字符串,needle就是子字符串,也就是说要在haystack中寻找needle字符串。找不到就返回NULL。
师承 上官可编程