1、配置文件
2、简单实现修改配置文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv) //不要写成char **argv[]
{
if (argc != 2){
printf("parama error\n");
exit(-1);
}
int fd_src;
fd_src = open(argv[1], O_RDWR);
if (fd_src > 0){
printf("fd_src = %d\n", fd_src);
}
int file_size = lseek(fd_src, 0, SEEK_END);
char *readBuf = NULL;
readBuf = (char *)malloc(file_size);
memset(readBuf, '\0', file_size);
lseek(fd_src, 0, SEEK_SET); //将光标移到文件首位置,再进行读取文件内容操作
int n_read = read(fd_src, readBuf, file_size);
printf("read %d bytes\n", n_read);
char *p = strstr(readBuf, "LENG=");
p = p + strlen("LENG=");
*p = '5';
//此时光标位于文件末尾
//将修改后的内容重新写入到该文件中,有两种方法:
//法1、将光标再次移到文件首位置,直接覆盖原先内容
//法2、open()时添加O_TRUNC参数,清楚先前内容
//法1、lseek(fd_src, 0, SEEK_SET);
fd_src = open(argv[1], O_RDWR | O_TRUNC); //法2
int n_write = write(fd_src, readBuf, strlen(readBuf));
printf("write %d bytes\n", n_write);
close(fd_src); //关闭文件
return 0;
}
3、运行代码,得到修改后的配置文件
成功将“LENG=3”修改为“LENG=5”