配置文件的初始内容:
现在要将166中的1改为6:
#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 fault\n");
exit(-1);
}
fdsrc = open(argv[1], O_RDWR); // 以可读写方式打开源文件
printf("fdsrc=%d\n", fdsrc);
int size = lseek(fdsrc, 0, SEEK_END); // 定位文件指针到文件末尾,并获取文件大小
printf("size=%d\n", size);
lseek(fdsrc, 0, SEEK_SET); // 将文件指针重新定位到文件开头
readbuf = (char*)malloc(sizeof(char) * (size + 5)); // 动态分配缓冲区内存空间,大小为文件大小加5个字节
int read_size = read(fdsrc, readbuf, size); // 从文件中读取数据到缓冲区
char* p = strstr(readbuf, "guoda:"); // 在读取的数据中查找 "guoda:" 字符串的位置
if (p == NULL) // 如果未找到 "guoda:" 字符串
{
printf("Not found\n");
exit(-1);
}
p = p + strlen("guoda:"); // 将指针移动到 "guoda:" 字符串之后的位置
*p = '6'; // 修改该位置的字符为 '6'
// ssize_t write(int fd, const void *buf, size_t count);
int write_size = write(fdsrc, readbuf, read_size); // 将修改后的数据写回文件
free(readbuf); // 释放动态分配的内存空间
close(fdsrc); // 关闭源文件描述符
return 0;
}
20230811