要求实现功能:
配置文件date1.c里有:
QWER=5
ABCD=6
ASDF=7
要求编写一个小程序把配置文件date1里的ABCD=6改成ABCD=8
编程思路:
1 进行参数传参。 int main(int argc,char** argv)
2 判断参数个数是否正确。
3 用open函数打开date1的文件
4 用read函数读取文件内容到buf
5 修改buf里的内容。修改思路:(1.用strstr函数 char *strstr(const char *haystack, const char *needle);第一个参数是查找的目标,第二个是查找的内容。成功返回值是查找的内容的首元素。失败返回NULL。2.返回的是首元素,要偏移到要修改的位置。所以首元素的指针要往后走。3.找到修改的位置修改)
6 用write函数把修改后的BUF写入配置文件。
7 关闭文件。
代码:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int argc,char **argv)
{
int fd;
char *readbuf=NULL;
fd=open("./text1",O_RDWR);
if(fd==-1){
perror("why");
exit(-1);
}
int size=lseek(fd,0,SEEK_END);
lseek(fd,0,SEEK_SET);
readbuf=(char *)malloc(sizeof(char)*size+6);
int nread=read(fd,readbuf,size);
if(nread==-1){
printf("read fail\n");
exit(-1);
}
char *p=strstr(readbuf,"ABCD=");
if(p==NULL){
printf("no find\n");
exit(-1);
}
p=p+strlen("ABCD=");
*p='8';
lseek(fd,0,SEEK_SET);
int nwrite=write(fd,readbuf,strlen(readbuf));
if(nwrite==-1){
printf("write fail\n");
exit(-1);
}
close(fd);
return 0;
}
结果:
CLC@Embed_Learn:~/fuxi$ cat text1
QWER=5
ABCD=6
ASDF=7
CLC@Embed_Learn:~/fuxi$ ./a.out
CLC@Embed_Learn:~/fuxi$ cat text1
QWER=5
ABCD=8
ASDF=7