INNER CODE UNIT · Python

write_file_atomic

ArcSurge/Termius-Pro-zh_CN · lang.py:93

def write_file_atomic(file_path, content=None, offsets=None):
    """原子写入文件:先写临时文件再替换,避免中断导致损坏(支持文本和二进制内容)

    Args:
        file_path: 文件路径
        content: 完整内容(bytes 走二进制,其他按 utf-8 文本写入),整体覆写时必填
        offsets: 局部补丁 {偏移: 补丁},提供时只在副本上改写补丁位置,
                 避免为改几个字节而整块读写(如数百 MB 的可执行文件)
    """
    file_dir = os.path.dirname(file_path) or "."
    temp_path = None
    try:
        if offsets:
            fd, temp_path = tempfile.mkstemp(dir=file_dir)
            os.close(fd)
            shutil.copyfile(file_path, temp_path)
            # mkstemp 默认 0600 且 copyfile 不带权限位,需还原,否则会丢掉可执行位
            shutil.copymode(file_path, temp_path)

View source record →

📰 Research Paper
Loading…
⏳ Fetching content…