Linux修改文件配置.config

man 手册
查找字符串 strstr API
修改会存在的问题解决

man 手册

SYNOPSIS			概要
DESCRIPTION			描述
RETURN VALUE		返回值
ATTRIBUTES			属性
CONFORMING TO		符合
SEE ALSO			参见
COLOPHON			出版社

查找字符串 strstr API

SYNOPSIS
       #include 

       char *strstr(const char *haystack, const char *needle);

       #define _GNU_SOURCE         /* See feature_test_macros(7) */

       #include 

       char *strcasestr(const char *haystack, const char *needle);
DESCRIPTION
       The  strstr() function finds the first occurrence of the substring nee‐
       dle in the string haystack.  The terminating null bytes ('\0') 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  sub‐
       string, or NULL if the substring is not found.

查找修改

可以用lseek()函数或者check()函数让光标回到开头

  1. 找到要修改的位置a
  2. 要修改的位置a后移,移动到b
  3. 修改b位置的内容
#include 
#include 
#include 
#include 
#include 
#include 
#include 

//整数类型主函数(整数类型统计参数个数,字符类型指针数组指向字符串参数)
int main(int argc,char **argv)
{
	int fdSrc;
	char *readBuf = NULL;

	//参数错误
	if(argc != 2){
		printf("param error\n");
		exit(-1);
	}
	
	//打开原文件Src	
	fdSrc = open(argv[1],O_RDWR);
	
	//计算文件大小并让光标回到头
	int size = lseek(fdSrc,0,SEEK_END);
	lseek(fdSrc,0,SEEK_SET);

	//开辟空间给buf并读取原文件Src
	readBuf = (char *)malloc(sizeof(char)*size + 8);
	int n_read = read(fdSrc,readBuf,size);

	//查找并修改数据
//char *strstr(const char *haystack, const char *needle);
	char *p = strstr(readBuf,"LENGTH=");
	if(p == NULL){
		printf("not found\n");
		exit(-1);
	}

	p = p+strlen("LENGTH=");
	*p = '5';
	lseek(fdSrc,0,SEEK_SET);

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

	//关闭文件
	close(fdSrc);

	return 0;
}

Linux修改文件配置.config_第1张图片

修改会存在的问题解决

	//查找并修改数据
//char *strstr(const char *haystack, const char *needle);
	char *p = strstr(readBuf,"LENGTH=");
	if(p == NULL){
		printf("not found\n");
		exit(-1);
	}

	p = p+strlen("LENGTH=");
	*p = '5';
	lseek(fdSrc,0,SEEK_SET);

如果修改的不是上面的字符而是直接写数据

	p = p+strlen("LENGTH=");
	*p = 5;
	lseek(fdSrc,0,SEEK_SET);

会出现下面的情况
Linux修改文件配置.config_第2张图片
Linux修改文件配置.config_第3张图片

你可能感兴趣的:(LINUX,linux,运维,服务器,c语言,ubuntu,算法)