【问题标题】:Replace the first line and save to a file in Matlab?替换第一行并保存到 Matlab 中的文件?
【发布时间】:2013-03-21 14:34:36
【问题描述】:

我正在尝试在 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

【问题讨论】:

  • 你不能用textscan吗?

标签: matlab


【解决方案1】:

要读入文件,更改第一行,然后将其写回,您可以执行以下操作:

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

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

【讨论】:

    猜你喜欢
    • 2016-10-20
    • 2011-07-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2020-08-15
    • 2023-04-05
    • 2014-04-04
    • 1970-01-01
    相关资源
    最近更新 更多