1

我正在尝试在 Matlab 中执行此操作,但它表明

使用 fget 时出错。文件标识符无效。使用 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
4

1 回答 1

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);

您收到的错误可能是因为您使用的文件名或路径无效。

于 2013-03-21T16:37:09.797 回答