MATLAB:如何将文件中的内容复制到旧文件的特定位置

时间:2015-02-06 13:40:37

标签: matlab file-io

我有两个文本文件:file1.txt& FILE2.TXT

file1.txt的内容:

Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;


My old contents(1);
My old contents(2);
My old contents(3);
My old contents(4);


Required contents of file;
Required contents of file;
Required contents of file;
Required contents of file;

file2.txt的内容:

My new var(1);
My new var(2);
My new var(3);
My new var(4); 

我有一个updateFile.m函数:试图用新的var替换file1.txt中的旧内容

function updateFile(file)

% Read the new contents
fid = fopen('file2.txt', 'r');
c1 = onCleanup(@()fclose(fid));
newVars = textscan(fid,'%s','Delimiter','\n');
newVars = newVars{1};

% Save the testfile in to a cellaray variable
fid = fopen(file, 'r');
c2 = onCleanup(@()fclose(fid));
oldContent = textscan(fid,'%s','Delimiter','\n');


% Search for specific strings
oldContentFound = strfind(oldContent{1},'My old contents(1);');
oldContentRowNo = find(~cellfun('isempty',oldContentFound));

% Move the file position marker to the correct line
fid = fopen(file, 'r+');
c3 = onCleanup(@()fclose(fid));
for k=1:(oldContentRowNo-1)
    fgetl(fid);
end

% Call fseek between read and write operations
fseek(fid, 0, 'cof');

for idx = 1:length(newVars)
    fprintf(fid, [newVars{idx} '\n']);
end

end

我面临的问题是,file1.txt仍然包含一些不需要的旧内容。任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

您可以在文件中添加一些字符,但不能删除一些字符。您必须使用具有正确内容的新文件擦除文件。

这是对你的功能的重写:

function updateFile(file)

% Read the new contents
fid = fopen('file2.txt', 'r');
newVars = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
newVars = newVars{1};

% Read the old content
fid = fopen(file, 'r');
f1 = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
f1 = f1{1};

% Find pattern start line
[~,k] = ismember('My old contents(1);', f1);

% Replace pattern
for i = 1:numel(newVars)
    f1{k+i-1} = newVars{i};
end

% Replace initial file
fid = fopen(file, 'w');
cellfun(@(x) fprintf(fid, '%s\n', x), f1);
fclose(fid);

最佳,

答案 1 :(得分:0)

文件访问本质上是基于字节的。没有在文件中间插入或删除内容的事情。在大多数情况下,最简单的方法是编辑内存中的内容,然后重写整个文件。

在您的情况下,在读取输入文件后,找到单元格数组中的起始行和结束行,并简单地用新数据替换它们。然后再次打开文件进行正常写入,并输出整个单元格数组。