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。