SPEED=3
LENG=9
SCORE=9
LEVEL=5
将LENG的值改成5.
首先先介绍一个函数用法strstr(),char *strstr(const char *haystack, const char *needle)
参数:
haystack – 要被检索的 C 字符串。
needle – 在 haystack 字符串内要搜索的小字符串。
返回值
该函数返回在 haystack 中第一次出现 needle 字符串的位置的地址,如果未找到则返回 null。
思路:
1、找到要修改的位置(使用strstr()函数)
2、在移动指针到LENG= 处。
3、修改
#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 fdScr;
char *readBuf=NULL;
if(argc!=2)
{
printf("Data arm error\n");
exit(-1);
}
fdScr=open(argv[1],O_RDWR);//创建源文件
int size=lseek(fdScr,0,SEEK_END);
lseek(fdScr,0,SEEK_SET);//注意把光标重新放回开头。
fdScr=open(argv[1],O_RDWR);//创建源文件
int size=lseek(fdScr,0,SEEK_END);
lseek(fdScr,0,SEEK_SET);//注意把光标重新放回开头。
readBuf=(char *)malloc(sizeof(char)*size+8);
int n_read=read(fdScr,readBuf,size);//把源文件读到buf中
char *p=strstr(readBuf,"LENG=");
if(p==NULL)
{
printf("not found");
exit(-1);
}
p=p+strlen("LENG=");//指针后移
*p='5';
lseek(fdScr,0,SEEK_SET);//注意把光标重新放回开头。
int n_write=write(fdScr,readBuf,strlen(readBuf));//把读到的内容写道目标文件里
close(fdScr);
return 0;