You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现文本子串匹配替换并保存至新文件的技术咨询

Solution: Substring Replacement and Save to Modified File

First, let's fix the bugs in your original code and add the replacement functionality step by step. Your existing code has a few issues (like mismatched file pointers, nested loops that don't make sense, and unhandled newline characters from input) that we'll address along with adding the core replacement feature.

Key Steps We'll Implement:

  • Open the original file in read-only mode (we'll never modify the original directly!)
  • Create a new file to write the modified content
  • Get both the target substring and replacement string from the user
  • Strip newline characters from user input (since fgets includes them when you press Enter)
  • For each line in the original file:
    • Check if the target substring exists
    • Replace all occurrences of the substring in the line
    • Write the modified (or original) line to the new file
  • Clean up by closing all file handles properly

Corrected and Enhanced Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LINE_LENGTH 1024

// Helper function to strip trailing newline from user input
void strip_newline(char *str) {
    char *newline = strchr(str, '\n');
    if (newline != NULL) {
        *newline = '\0';
    }
}

// Helper function to replace all occurrences of a substring in a string
char* replace_substring(const char *original, const char *search, const char *replace) {
    char *result;
    int search_len = strlen(search);
    int replace_len = strlen(replace);
    int count = 0;
    const char *temp = original;

    // Count how many times the search string appears to allocate enough memory
    while ((temp = strstr(temp, search)) != NULL) {
        count++;
        temp += search_len;
    }

    // Allocate memory for the modified string
    result = (char*)malloc(strlen(original) + count * (replace_len - search_len) + 1);
    if (result == NULL) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    char *ptr = result;
    temp = original;

    // Replace each occurrence one by one
    while ((temp = strstr(temp, search)) != NULL) {
        // Copy characters from original up to the search string
        strncpy(ptr, original, temp - original);
        ptr += temp - original;

        // Copy the replacement string
        strcpy(ptr, replace);
        ptr += replace_len;

        // Move past the search string in the original
        original = temp + search_len;
        temp = original;
    }

    // Copy the remaining part of the original string
    strcpy(ptr, original);
    return result;
}

int main() {
    // Open original file in read mode
    FILE *original_file = fopen("C:\\Users\\Luther\\Desktop\\txtfiles\\words.txt", "r");
    if (original_file == NULL) {
        perror("Error opening original file");
        return EXIT_FAILURE;
    }

    // Create new file for modified content
    FILE *modified_file = fopen("C:\\Users\\Luther\\Desktop\\txtfiles\\modified_words.txt", "w");
    if (modified_file == NULL) {
        perror("Error creating modified file");
        fclose(original_file);
        return EXIT_FAILURE;
    }

    char search_str[MAX_LINE_LENGTH];
    char replace_str[MAX_LINE_LENGTH];
    char line[MAX_LINE_LENGTH];

    // Get user input for search and replacement strings
    printf("Enter the substring to search for: ");
    fgets(search_str, MAX_LINE_LENGTH, stdin);
    strip_newline(search_str);

    printf("Enter the replacement substring: ");
    fgets(replace_str, MAX_LINE_LENGTH, stdin);
    strip_newline(replace_str);

    // Guard against empty search string to avoid infinite loops
    if (strlen(search_str) == 0) {
        fprintf(stderr, "Error: Search string cannot be empty.\n");
        fclose(original_file);
        fclose(modified_file);
        return EXIT_FAILURE;
    }

    // Process each line in the original file
    while (fgets(line, MAX_LINE_LENGTH, original_file) != NULL) {
        char *modified_line = line; // Default to original line if no replacement needed

        // If search string is found, replace all occurrences
        if (strstr(line, search_str) != NULL) {
            modified_line = replace_substring(line, search_str, replace_str);
        }

        // Write the line to the modified file
        fputs(modified_line, modified_file);

        // Free dynamically allocated memory only if we did a replacement
        if (modified_line != line) {
            free(modified_line);
        }
    }

    // Clean up resources
    fclose(original_file);
    fclose(modified_file);
    printf("Modification complete! Modified content saved to modified_words.txt\n");

    return EXIT_SUCCESS;
}

Important Notes:

  • File Paths: Double-check the paths to your original and modified files. The code uses your existing path for the original file and creates modified_words.txt in the same directory.
  • Memory Safety: The replace_substring function dynamically allocates memory for modified lines, which we free immediately after writing to avoid memory leaks.
  • Edge Cases: We handle empty search strings and file open errors to provide clear, actionable error messages.
  • Newline Preservation: The code keeps the original line breaks intact in the modified file.

内容的提问来源于stack exchange,提问作者ImSkilzBTW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:53:10