1.首先我们前面介绍了那么多关于文件的api,今天来记录一下strstr
函数。
函数原型:
char *strstr(const char *haystack, const char *needle);
返回值:返回一个char
型的指针,(返回一个指针指向目的字符串开头位置的指针),如果没有找到的话,则返回NULL
。
作用:用于判断字符串needle
是否是haystack
的子串;如果是,则该函数返回needle
在haystack
中首次出现的地址;否则返回NULL
。
haystack
:将要被查找的目标字符串。
needle
:将要被查找的对象字符串。
上代码:
pstr = strstr(readBuf,"YTRE=");
if(pstr == NULL)
{
printf("faild to found\n");
exit(-1);
}
pstr = pstr + strlen("YTRE=");
*pstr = '7';
修改YTRE=后面的数字:在readBuf缓冲区中读取“YTRE=”的字符串的首位,并返回给指针pstr,指针接收到后进行指针的偏移“YTRE=”那么长的长度,再将偏移后的指针的位置的内容修改即可,最后写回原来的文件中。
直接上代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if(argc != 2)
{
printf("parameter error!!\n");
exit(-1);
}
int fd;
int fd_size;
char *readBuf = NULL;
char *pstr = NULL;
fd = open(argv[1],O_RDWR);
fd_size = lseek(fd,0,SEEK_END);
lseek(fd,0