Assume that a file exists. How to replace the occurrence of a character with another character?

Dani AI

Generated

Three safe, practical ways to replace a character in a file:

  • Stream-to-temp-file and rename: robust for large files and crash-safe (recommended).
  • Read whole file into memory, modify, write back: simple and fast for small files (as suggested).
  • In-place overwrite: only safe when the replacement is the same byte-length and the file encoding/semantics allow it.

As noted, online examples exist, but it helps to write and test a short implementation. The streaming approach below is the most generally useful: read chunks, patch bytes, write to a temporary file, then atomically replace the original (POSIX) or remove+rename on platforms that require it.

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

int replace_char_stream(const char *path, unsigned char from, unsigned char to)
{
    FILE *in = fopen(path, "rb");
    if (!in) return -1;
    char tmp[1024];
    snprintf(tmp, sizeof tmp, "%s.tmp", path); /* simple temp name; use mkstemp on POSIX for security */
    FILE *out = fopen(tmp, "wb");
    if (!out) { fclose(in); return -2; }
    unsigned char buf[8192];
    size_t n;
    while ((n = fread(buf, 1, sizeof buf, in)) > 0) {
        for (size_t i = 0; i < n; ++i) if (buf[i] == from) buf[i] = to;
        if (fwrite(buf, 1, n, out) != n) { fclose(in); fclose(out); remove(tmp); return -3; }
    }
    fclose(in); fclose(out);
    if (rename(tmp, path) != 0) { remove(tmp); return -4; } /* POSIX: atomic; on Windows remove old first */
    return 0;
}

If the replacement is guaranteed to be a single byte and it is acceptable to modify the file in place, this simpler method works:

#include <stdio.h>

int replace_char_inplace(const char *path, unsigned char from, unsigned char to)
{
    FILE *f = fopen(path, "r+b");
    if (!f) return -1;
    int c;
    while ((c = fgetc(f)) != EOF) {
        if ((unsigned char)c == from) {
            if (fseek(f, -1, SEEK_CUR) != 0) { fclose(f); return -2; }
            if (fputc(to, f) == EOF) { fclose(f); return -3; }
        }
    }
    fclose(f);
    return 0;
}

Troubleshooting and cautions: always check return values, open files with binary mode to avoid CR/LF translation on Windows, prefer unsigned char when comparing bytes, and back up important files. Do not attempt byte-level edits on UTF-8 multibyte characters (use a Unicode-aware library if the target may be multibyte). For secure temp files on POSIX use mkstemp; to preserve permissions/metadata use stat/fchmod if needed.

Recommended Answers

All 2 Replies

Is this your assignment or something else? looks complete but if this is homework, ignore the web and write something. Share your code and tell why you think it didn't work.

If the file will all fit into memory, then the better (much faster) method is to read the whole file into dynamic memory ... traverse that data and update as desired ... then write all that updated data back to the (overwritten) file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.