Linux 文件 查找文件的内容,实现修改

19 篇文章 0 订阅

注:Linux 文件 查找文件的内容,实现修改(10节)

查找文件的内容,实现修改

一、分为5步
1、打开文件
2、读取文件
3、找到我们需要的内容
4、修改内容,重写文件内容
5、关闭文件
二、代码实现如下:demo13.c

#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 agrc,char **agrv)
{
	int fdSrc;
	fdSrc=open(agrv[1], O_RDWR);//打开目标文件,文打开件的权限	O_RDWR
	if(agrc != 2){
		printf("Input error!!!");
		exit(-1);
	}//运行时要输入两个目标的位置

	int filesize=lseek(fdSrc,0,SEEK_END);//利用光标读取文件的大小 
	lseek(fdSrc,0,SEEK_SET);//光标回归起始位置 

	char *rd_buf = NULL;
	rd_buf=(char *)malloc(sizeof(char)*filesize + 8);
//	ssize_t read(int fd, void *buf, size_t count);
	read(fdSrc,rd_buf,filesize);//读取文件,读取fdSrc的内容 到 rd_buf 
	
        //char *strstr(const char *haystack, const char *needle);
	char *p=strstr(rd_buf,"LEEK =");//找到 LEEK = 
	if( p == NULL){
		printf("NOT Found!!\nexit(-1)");
		exit(-1);
	}
	printf("p=%s\n",p);
	//地址++到 第8个位置
	p=p+strlen("LEEK =0");//找到之后,改变我们所需要的位置 
	*p = '9';//这里只能修改是一个字符 
	printf("p=%s\n",p);
	lseek(fdSrc,0,SEEK_SET);
	//	ssize_t write(int fd, const void *buf, size_t count);
	int n_write=write(fdSrc,rd_buf,strlen(rd_buf));

	close(fdSrc);	
	return 0;
}

三、运行效果:
revamp.config文件的内容:

SEEK = 5
LEEK = 3
LIFE = 10

编译运行成功
./a.out revamp.config

SEEK = 5
LEEK = 9
LIFE = 10

测试:code:test5.c

CLC@Embed_Learn:~/test$ cat test5.c
#include<string.h>
#include<stdio.h>
#include <string.h>
int main()
{
	char *p=NULL;
	char *string1="needle in haystack";
	char *string2="ha";
	p=strstr(string1, string2);
	printf("%s\n",p);
	
	p=p+strlen("ha");
	printf("%s\n",p);
	*p='i';	//这句话出现段错误
	
	printf("%s\n",p);
	return 0;
}

运行结果:
//test fail
CLC@Embed_Learn:~/test$ ./a.out
haystack
ystack
Segmentation fault (core dumped)//分段故障

测试:code:test6.c

#include<string.h>
#include<stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
	
	char *p = "needle in haystack";

	p=p+strlen("ha");
	printf("%s\n",p);
	
	*p= 'i';//出现段错误,不允许这样操作(只有在文件中的时候允许查看上述代码:demo13.c)
	printf("%s\n",p);
	return 0;
}
小结
  • 和demo13.c比较的话会出现段错误,说明测试的这情况不能单独使用,只有在对文件进行操作的时候才可以这样。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值