linux下编程修改配置文件

假设我的test.config文件内容是:

SPEED=3
LENG=5
SCORE=8
LEVEL=5

通过文件操作,来把LENG=5修改为LENG=3

实现该功能的基本是思路如下:

    1.读取配置文件到缓存中
    2.strstr查找子字符串寻找位置,查找asdf=返回的是a的位置
    3.指针位置+便宜(strlen("LENG="))
    4.*p 取内容,被赋值= 修改
    5.写入操作是文件,是字符

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


int main(int  argc ,char **argv)
{
        char *readBuff = NULL;
        int fdSrc;
        if(argc != 2){                      //./a.out test.config   argc=2
                printf("pararm error\n");
                exit(-1);
        }

        fdSrc = open(argv[1],O_RDWR);

        int size = lseek(fdSrc,0,SEEK_END);
        readBuff =(char *)malloc(sizeof(char)*size+8);

        lseek(fdSrc,0,SEEK_SET);

        int n_read = read(fdSrc,readBuff,size);


        char *p = strstr(readBuff,"LENG=");
        if(p == NULL){
                printf("not found\n");
                exit(-1);
        }
        p = p + strlen("LENG=");

        *p = '3';     //写入的是字符因此是''


        lseek(fdSrc,0,SEEK_SET);



        int n_write = write(fdSrc,readBuff,strlen(readBuff));

        close(fdSrc);


         return 0;
  }


 

猜你喜欢

转载自blog.csdn.net/qq_44848795/article/details/123566853
今日推荐