修改文件中的%d的会出错,如何解决?错误代码-1073741819

错误窗口。修改文件中的%d类型的会直接结束运行,改%s类型的能正常运行

img

代码

img

img

文件位置

img

img

【以下回答由 GPT 生成】

根据你提供的信息,错误代码-1073741819表示程序发生了堆栈溢出的错误。从截图也可以看到,你使用了递归函数replaceFileContent。这可能是导致堆栈溢出的原因之一。

为了解决这个问题,我建议你使用迭代而不是递归的方式进行文件内容的替换。以下是修改后的代码示例:

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

void replaceFileContent(const char *filename) {
    FILE *file = fopen(filename, "r+");
    if (file == NULL) {
        printf("无法打开文件\n");
        return;
    }

    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&line, &len, file)) != -1) {
        char *ptr = line;
        char *newLine = (char *)malloc(len * sizeof(char));
        char *newPtr = newLine;
        int isReplaced = 0;

        while (*ptr != '\0') {
            if (*ptr == '%' && *(ptr + 1) == 'd') {
                int value = 100;  // 这里可以根据实际情况替换为你想要的数值
                sprintf(newPtr, "%d", value);
                newPtr += strlen(newPtr);
                ptr += 2;
                isReplaced = 1;
            } else {
                *newPtr++ = *ptr++;
            }
        }

        if (isReplaced) {
            *newPtr = '\0';
            fseek(file, -read, SEEK_CUR);
            fputs(newLine, file);
        }

        free(newLine);
    }

    free(line);
    fclose(file);
}

int main() {
    const char *filename = "path_to_your_file.txt";
    replaceFileContent(filename);
    return 0;
}

这段代码使用了getline函数逐行读取文件内容,并且使用fseekfputs函数进行替换后的写操作。请将代码中的path_to_your_file.txt替换为你的文件路径。

希望对你有帮助!如果还有其他问题,请随时提问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

修改如下,供参考:

img