How to Implement File-Based String Replacement in C: A Step‑by‑Step Guide
This article walks through the design and implementation of a C program that reads a text file, replaces all occurrences of a target substring with a new string using low‑level pointer operations, and writes the modified content back to the file, complete with memory‑allocation calculations and code examples.
Introduction
The author received a request to create a simple text‑replacement utility similar to the "Find and Replace" feature in a notepad. To help others facing the same problem, the full solution and its underlying logic are shared.
Requirement
Read the entire content of a file, replace every occurrence of a specified string with another string, and write the result back to the same file. While high‑level languages can do this in one or two lines, implementing it in C requires careful handling of pointers and dynamic memory.
Approach
The solution allocates two buffers: ori_str for the original file content and rst_str for the processed result. The program first reads the file, then copies unchanged portions to rst_str and inserts the new string wherever the old string is found.
The following diagram (originally included in the source) illustrates the memory layout and copy process:
Key Code Snippets
1. Calculate file length
int file_len = lseek(fd, 0, SEEK_END);
lseek(fd, 0, SEEK_SET);2. Truncate the file before rewriting
ftruncate(fd, 0);3. Compute the length of the result buffer
int rst_str_len = file_len + n * abs(strlen(new_str) - strlen(old_str)) + 1;Here n is the number of matches, obtained by a helper substr_count function that repeatedly calls strstr to count occurrences.
4. Core replacement loop
while ((end_ptr = strstr(begin_ptr, old_str)) != NULL) {
memcpy(cpy_str, begin_ptr, end_ptr - begin_ptr);
cpy_str += (end_ptr - begin_ptr);
memcpy(cpy_str, new_str, strlen(new_str));
cpy_str += strlen(new_str);
end_ptr += strlen(old_str);
begin_ptr = end_ptr;
}
strcpy(cpy_str, begin_ptr);After processing, the program seeks back to the file start (because ftruncate leaves the file pointer at the end) and writes rst_str back to the file.
Conclusion
The presented method demonstrates low‑level file handling, dynamic memory management, and string manipulation in C, offering a reusable pattern for similar text‑processing tasks on Linux systems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
