linux的strstr函数

strstr函数原型:

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

haystack:要查找目标的地址。

needle:要查找目标的字符串。

返回一个char型指针,如果找不到的话就返回NULL


int main(int argv,char **argc)
{
        int fdDir;
        char *readbuf=NULL;
        if(argv!=2){
                printf("program error");
                exit(-1);
        }


        fdDir=open(argc[1],O_RDWR);
        int size=lseek(fdDir,0,SEEK_END);
        lseek(fdDir,0,SEEK_SET);
        readbuf=(char*)malloc(sizeof(char)*size+8);
        read(fdDir,readbuf,size);

        char *p=strstr(readbuf,"new=");
        if(p==NULL){
        printf("no found\n");
        exit(-1);
        }
        p=p+strlen("new=");
        *p='9';
        lseek(fdDir,0,SEEK_SET);

        write(fdDir,readbuf,strlen(readbuf));

        close(fdDir);
        return 0;
}
num=1;
new=2;
class=3;
Onepice=4;

该代码实现的是将new=后面的数字‘2’修改为数字‘9’;

思想:先找到原文件的‘new=’,然后偏移将光标定位在‘new=’后,接着就修改,因为光标发生了偏移,所以要把光标返回到头部再写入。

Linux写结构体数组到文件

struct Test
{
        int a;
        char c;
};
int main()
{
        int fd;
        struct Test data[2]={{5,'a'},{6,'b'}};
        struct Test data2[2];
        fd=open("./file1",O_RDWR);
        int n_write=write(fd,&data,sizeof(struct Test)*2);

        lseek(fd,0,SEEK_SET);
        int n_read=read(fd,&data2,sizeof(struct Test)*2);
        printf("read %d,context:%d,context:%c\n",n_read,data2[0].a,data2[0].c);
        printf("read %d,context:%d,context:%c\n",n_read,data2[1].a,data2[1].c);
        close(fd);
        return 0;
}

1.打开文件。

2.将文件通过文件描述符写入data。

3.将光标移到前面。

4.通过文件描述符fd指定的文件读取数据到data2。

这样就实现了结构体写入文件夹。

但我们打开该文件夹是显示的是不正常的字符,这是正常现象,对于机器来说他是正常的,人为观看是看不懂的。

注意:因为是2个数组,所以写入的大小要*2。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值