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

如何将TXT文件内容追加至另一文件且保留格式(Matlab代码问题)

Fixing Format Loss When Merging Text Files in MATLAB

The problem with your current code is that you’re opening files in text mode (without the b flag), which can cause MATLAB to automatically convert line endings (like \n to \r\n on Windows) or mishandle special characters. Additionally, using textscan with %c might not preserve the exact byte structure of the original files.

A more reliable approach is to read and write the files in binary mode, which ensures every character—including line breaks, tabs, and special symbols—is copied exactly as it appears in the source files. Here's how to adjust your code:

% Open destination file in append BINARY mode to preserve all formatting
destFileId = fopen(destFile, "ab");
if destFileId == -1
    error("Failed to open destination file: %s", destFile);
end

% Open source file in read BINARY mode
sourceFileId = fopen(sourceFile, "rb");
if sourceFileId == -1
    fclose(destFileId); % Clean up if source can't be opened
    error("Failed to open source file: %s", sourceFile);
end

% Read entire source file as raw bytes
content = fread(sourceFileId, "*char"); % Read as character array

% Append content to destination if there's data to write
if ~isempty(content)
    fwrite(destFileId, content, "char");
end

% Close both files
fclose(sourceFileId);
fclose(destFileId);

Key Improvements:

  • Binary Mode: Using "rb" (read binary) and "ab" (append binary) prevents MATLAB from modifying line endings or interpreting special characters, ensuring the original format is preserved.
  • Raw Byte Reading: fread with "*char" reads the entire file as a single character array, capturing every byte exactly as it exists in the source.
  • Error Handling: Added checks to ensure files open successfully, and clean up resources if something goes wrong.

If you need to merge multiple .txt files at once, wrap this code in a loop over your list of source files:

sourceFiles = dir("*.txt"); % Get all .txt files in current directory
destFile = "merged_output.txt";

for file = sourceFiles'
    sourceFile = file.name;
    % Insert the code block above here to append each sourceFile to destFile
end

This will merge all your text files into merged_output.txt without altering any formatting.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:44:21