Linux修改文件配置.config

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

man 手册

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

查找字符串 strstr API

SYNOPSIS
       #include <string.h>

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

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

       #include <string.h>

       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 <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)
{
	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;
}

请添加图片描述

修改会存在的问题解决

	//查找并修改数据
//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);

会出现下面的情况
请添加图片描述
请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咖喱年糕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值