朋友们可以讲解一下这个代码吗?(尽量详细一点好吗,麻烦了)读取文件到内存是分配给字符串吗?特别是字符串搜索那一部分的,里边的for循环和if语句不是太明白,感谢
#include <stdio.h>#include <string.h>
#include <memory.h>
#include <malloc.h>
const char* TARGET_FILE = "C:\\Users\\Lubin\\Desktop\\test.txt";
const char* target_string_val = "hello";
const char* replace_string_val = "how are you";
int main(void)
{
FILE* fp = NULL;
long i, size = 0L;
char* mem, *tmp;
size_t target_string_len;
size_t replace_string_len;
target_string_len = strlen(target_string_val);
replace_string_len = strlen(replace_string_val);
/* 打开文件 */
fp = fopen(TARGET_FILE, "rb");
if (NULL == fp) {
perror("fopen failed");
goto END;
}
/* 获取文件大小 */
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("=== File size is %ld bytes\n", size);
if (size < target_string_len) {
printf("no match\n");
goto END;
}
/* 读取全部文件到内存 */
mem = (char*)calloc(size, 1);
if (NULL == mem) {
perror("calloc failed");
goto END;
}
fread(mem, 1, size, fp);
tmp = mem;
/* 重开文件用于写 */
fclose(fp);
fp = fopen(TARGET_FILE, "wb");
/* 字符串搜索 */
for (i = 0L; i <= size - target_string_len; ++i) {
if (memcmp(mem + i, target_string_val, target_string_len) == 0) {
printf("== find match at offset %ld\n", i);
/* 写入开始到目标字符串的内容 */
if (mem + i - tmp) {
printf("== write %ld bytes header\n", mem + i - tmp);
fwrite(tmp, 1, mem + i - tmp, fp);
}
/* 写入替换字符串 */
printf("== write replace string\n");
fwrite(replace_string_val, 1, replace_string_len, fp);
tmp = mem + i + target_string_len;
printf("== update tmp = %s\n", tmp);
i += target_string_len - 1;
}
}
/* 写入尾部(结尾不是目标字符串的情况) */
if (tmp < (mem + size)) {
printf("== write tail %ld bytes\n", mem + size - tmp);
fwrite(tmp, 1, mem + size - tmp, fp);
}
printf("=== Replace END\n");
fclose(fp);
free(mem);
//pause
END:
getchar();
return 0;
}
[此贴子已经被作者于2019-9-15 18:56编辑过]