注: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比较的话会出现段错误,说明测试的这情况不能单独使用,只有在对文件进行操作的时候才可以这样。