栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux文件编程练手项目

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux文件编程练手项目

Linux文件编程练手项目

已经存在配置文件,名称为TEST.config,其内容如下:

SPEED=3
LENG=5
SCORE=9
LEVEL=5

现需要修改其内容,将SCORE的值修改为5

通过man手册查阅strstr函数的使用,如下所示:

NAME
strstr, strcasestr - locate a substring

SYNOPSIS
#include

   char *strstr(const char *haystack, const char *needle);

   #define _GNU_SOURCE         

   #include 

   char *strcasestr(const char *haystack, const char *needle);

DEscriptION
The strstr() function finds the first occurrence of the substring needle in
the string haystack. The terminating null bytes (’’) are not compared.

   The strcasestr() function is like strstr(), but  ignores  the  case  of  both
   arguments.

RETURN VALUE
These functions return a pointer to the beginning of the located substring,
or NULL if the substring is not found.

代码实现如下所示:

#include
#include
#include
#include
#include
#include
#include

int main(int argc,char **argv)
{
        int fdSrc;
        char *readBuf=NULL;
        if(argc!=2){
                printf("参数传递错误n");
                exit(-1);
        }
        fdSrc=open(argv[1],O_RDWR);
        int size=lseek(fdSrc,0,SEEK_END);
        lseek(fdSrc,0,SEEK_SET);
        readBuf=(char *)malloc(sizeof(char)*size+8);
        int n_read=read(fdSrc,readBuf,size);

        char *p=strstr(readBuf,"SCORE=");
        if(p==NULL){
                printf("not found!!!n");
                exit(-1);
        } 
        p=p+strlen("SCORE=");
        *p = '5';

        lseek(fdSrc,0,SEEK_SET);//此处需注意将光标回到开始位置
        int n_write=write(fdSrc,readBuf,strlen(readBuf));

        close(fdSrc);

        return 0;
}

执行结果如图所示:

1 .没有执行前

2.执行代码:

3.查看执行后的文件内容

4.结果如下:


通过这个小练手项目来进一步了解文件编程。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289383.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号