写一个TEST.config文件:
SPEED=5
LENG=100
SCORE=90
LEVEL=95
.config文件是linux内核配置文件
对TEST.config文件内容进行修改,将LENG=100,改成LENG=500
代码演示,建立一个demo13.c的文件:
#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 fdsrc;
char *readbuf=NULL;
if(argc!=2){
printf("pararm error\n");
exit(-1);//tuichugaichengxu
}
//打开文件,将文件复制到readbuf中
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);
//找到readbuf中LENG=中的位置,将位置移动到1,替换为5
char *p=strstr(readbuf,"LENG=");
if(p==NULL){
printf("not found\n");
exit(-1);
}
p=p+strlen("LENG=");
*p='5';
//移动光标到文件头,重新将readbuf中的内容写入到打开的文件中
lseek(fdsrc,0,SEEK_SET);
int n_write=write(fdsrc,readbuf,strlen(readbuf));
close(fdsrc);
return 0;
}
编译:gcc demo13.c
运行:./a.out TEST.config
运行结果为:
SPEED=5
LENG=500
SCORE=90
LEVEL=95
该文章展示了如何使用C语言编写程序来读取并修改名为TEST.config的文件内容,特别是将LENG=100更改为LENG=500。程序通过查找指定字符串,替换目标值,然后将修改后的内容写回文件。

676

被折叠的 条评论
为什么被折叠?



