How is it possible to delete a byte ( char, int, double .. ) from a text file ?

Suppose that the file.txt contains :"110Hello". And I want to delete "110" from the file leaving only the "Hello" part.

How to do this without reading the whole file into the memory and then rewriting the edited data ?

Thanks.

Dani AI

Generated

As and noted, filesystems do not provide a primitive to remove a span of bytes in the middle of a file without moving the bytes that follow. The operation is therefore always going to involve copying the trailing data forward and then shrinking the file. That can be done without loading the entire file into memory by streaming or by shifting blocks in place.

Two practical patterns that avoid high memory use:

  • Safe/simple: write the bytes to keep into a temporary file in fixed-size blocks (for example 8–64 KB), then atomically replace the original with the temp file. This is simple and crash-safe on POSIX when using rename.
  • In-place shift: open the file read/write, set readPos = offset + lengthToRemove and writePos = offset. Loop: read a block from readPos, write it at writePos, advance both positions, repeat until EOF, then truncate the file to writePos (ftruncate/SetEndOfFile). Memory-mapping and memmove is another option but beware very large files.

Pseudocode for the in-place shift:

open file "r+b"
readPos = offset + length
writePos = offset
while readPos < filesize:
    buf = read up to BUFSIZE from readPos
    write buf at writePos
    readPos += len(buf)
    writePos += len(buf)
ftruncate(file, writePos)
close file

Caveats: use file locking to prevent concurrent access, preserve encoding integrity (deleting bytes in UTF-8 can corrupt characters), and prefer temp-file+rename for better crash/atomic behavior. For many small edits or indexed records, consider a format or database that supports deletions instead of editing plain text files repeatedly.

Recommended Answers

All 2 Replies

you have to completly rewrite the file -- read the file into memory then write it back out but omitting the part you want to delete.

You can't. You need to read old and write new.

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.