文件编程应用之修改程序的配置文件
1.file1中有如下内容,我要将LENG = 10改成LENG = 3,应该如何操作?
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aaa19ae5315c974038ab06e41ad188b9.png)
2.程序源码如下:
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc,char **argv)
{
int fd;
char *readbuf=NULL;
fd=open(argv[1],O_RDWR);
int size=lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
readbuf=(char *)malloc(sizeof(char)*size+8);
int n_read=read(fd,readbuf,size);
lseek(fd,0,SEEK_SET);
char *p=strstr(readbuf,argv[2]);
if(p == NULL)
{
printf("no find");
exit(-1);
}
p=p+strlen(argv[2]);
*p='5';
write(fd,readbuf,strlen(readbuf));
close(fd);
}
3.前面的都是一些打开文件读取文件的操作,主要看strstr这个函数,在man手册中,函数原型如下:
#include <string.h>
char *strstr(const char *haystack, const char *needle);
haystack:一般是你从文件中读取内容,上面的例子就是从file1文件中从头到尾部读取的内容;
needle:你需要从这段内容中进行操作的字符串,比如我要改变的值是LENG=后面的数,则needle就赋值为"LENG=".
返回值为needle前面,即L前面,所以下面更改LENG的值才需要偏移指针。
4.运行结果如下: