项目实现中有时候需要根据一些设置的值替换掉代码文件中的一些字符串,让显示有所变化,这里有两种方式替换
利用查找字符串方式:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace_string_in_js_file(const char *filename, const char *old_str, const char *new_str) {
// 打开文件
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
// 获取文件大小
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
fseek(file, 0, SEEK_SET);
// 分配内存以存储文件内容
char *file_content = (char *)malloc(file_size + 100);
if (file_content == NULL) {
perror("Memory allocation failed");
fclose(file);
return;
}
// 读取文件内容
fread(file_content, 1, file_size, file);
file_content[file_size] = '\0'; // 确保字符串正确终止
// 替换字符串
char *pos = file_content;
long offset = 0; // 用于记录偏移量
while ((pos = strstr(pos, old_str)) != NULL) {
// 计算新字符串的长度差异
int old_len = strlen(old_str);
int new_len = strlen(new_str);
int diff = new_len - old_len;
//printf("%d\n", diff);
// 移动剩余的字符串
memmove(pos + new_len, pos + old_len, file_size - (pos - file_content) - old_len + 1);
// 替换字符串
memcpy(pos, new_str, new_len);
// 更新文件大小
file_size += diff;
// 更新指针位置
pos += new_len;
// 更新偏移量
offset += diff;
}
// 回到文件开始处并写入新内容
fclose(file);
file = fopen(filename, "w"); // 清空原本内容
fseek(file, 0, SEEK_SET);
fwrite(file_content, 1, file_size, file);
// 清理
free(file_content);
fclose(file);
}
int main() {
const char *filename = "C:\\Users\\haiyangjiang\\Desktop\\example.js"; // 你的JS文件名
replace_string_in_js_file(filename, "b", "linux");
return 0;
}
将文件打开,利用strstr函数查找到第一个匹配的子字符串,将内容拼接后替换,该代码不能替换有换行的代码文本,且容易造成内存溢出,十分不稳定
利用linux命令替换:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace_string_from_file(const char* file_path, int oemid) {
const char* old_str[] = {"Time Server 3001", "Time Server 3002"};
const char* new_str[] = {"Time Server 3001", "Time Server 3002"};
char cmd[254];
int len = sizeof(old_str) / sizeof(old_str[0]);
for (int i = 0; i < len; i++) {
if (i != oemid) {
snprintf(cmd, sizeof(cmd), "sed -i \"s/%s/%s/\" %s", old_str[i], new_str[oemid], file_path);
printf("replace string cmd: %s\n", cmd);
system(cmd);
memset(cmd, 0, sizeof(cmd));
}
}
}
int main() {
const char* filename = "/home/saisi/Desktop/Myproject/a.js"; // 你的JS文件名
replace_string_from_file(filename, 1);
return 0;
}
linux中sed -i "s/old_string/new_string/" /etc/filename.txt
能将文本中的filename文本中的所有old_string换成new_string如果匹配不到old_string就不替换,利用这个命令实现的函数能解决了上述函数的问题
linux查找文件sudo find / -name "*.txt" 可以对全局文件做查找操作,找到所有目标文件的位置