Linux里的指定修改数据

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;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值