我试图在Matlab中这样做,但它显示了
使用fgets时出错。文件标识符无效。使用fopen生成有效的文件标识符。
任何人都可以帮忙解决这个问题吗?提前谢谢。
以下是我的语法:
function [ ] = replaceStr(fidInFile, DIF(k), DIF(k+1))
for k = 1:100
fidInFile = fopen(['Rasch' num2str(k) '.inp'],'r');
fidOutFile = fopen(['Rasch' num2str(k+1) '.inp'],'w');
nextLine= fgets(fidInFile);
while nextLine >= 0
nextLine = strrep(nextLine,['DATA=DIF' num2str(k) '.dat'], ['DATA=DIF' num2str(k+1) '.dat']);
fprintf(fidOutFile,'%s', nextLine);
nextLine=fgets(fidInFile);
end
fclose(fidInFile);
fclose(fidOutFile);
end
答案 0 :(得分:0)
要读入文件,请更改第一行,然后将其写回,您可以执行以下操作:
% open files
fidIn = fopen('test.txt');
fidOut = fopen('test2.txt','w');
% read in file
tline = fgets(fidIn);
index = 1;
while ischar(tline)
data{index} = tline;
tline = fgets(fid);
index = index + 1;
end
% replace first row
data{1,1} = 'Something else';
% write to second file
for l = data
fprintf(fidOut,'%s\n', l{1,1});
end
fclose(fidIn);
fclose(fidOut);
您获得的错误可能是因为您使用的文件名或路径无效。