已经存在配置文件,名称为TEST.config,其内容如下:
SPEED=3
LENG=5
SCORE=9
LEVEL=5
现需要修改其内容,将SCORE的值修改为5
通过man手册查阅strstr函数的使用,如下所示:
NAME
strstr, strcasestr - locate a substring
SYNOPSIS
#include
char *strstr(const char *haystack, const char *needle); #define _GNU_SOURCE #includechar *strcasestr(const char *haystack, const char *needle);
DEscriptION
The strstr() function finds the first occurrence of the substring needle in
the string haystack. The terminating null bytes (’ ’) are not compared.
The strcasestr() function is like strstr(), but ignores the case of both arguments.
RETURN VALUE
These functions return a pointer to the beginning of the located substring,
or NULL if the substring is not found.
代码实现如下所示:
#include#include #include #include #include #include #include int main(int argc,char **argv) { int fdSrc; char *readBuf=NULL; if(argc!=2){ printf("参数传递错误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+8); int n_read=read(fdSrc,readBuf,size); char *p=strstr(readBuf,"SCORE="); if(p==NULL){ printf("not found!!!n"); exit(-1); } p=p+strlen("SCORE="); *p = '5'; lseek(fdSrc,0,SEEK_SET);//此处需注意将光标回到开始位置 int n_write=write(fdSrc,readBuf,strlen(readBuf)); close(fdSrc); return 0; }
执行结果如图所示:
1 .没有执行前
2.执行代码:
3.查看执行后的文件内容
4.结果如下:
通过这个小练手项目来进一步了解文件编程。



