如何将TXT文件内容追加至另一文件且保留格式(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:
freadwith"*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

