【问题标题】:Reading and writing to a file matlab读取和写入文件 matlab
【发布时间】:2013-10-17 05:35:45
【问题描述】:

我想从文件中读取数据并将其保存到数组中。然后在这个数组中插入一些新数据,然后将这些新数据保存回同一个文件中,删除已经存在的文件。我的代码完美运行,给了我所需的数据,当我在 fopen 参数中有 'r+' 时,但是当我再次写入文件时,它不会删除文件中已经存在的数据,只是按预期将其附加到末尾。但是,当我将权限更改为“w+”而不是“r+”时,我的代码运行但没有数据被读入或写入文件!有谁知道为什么会这样?我的代码如下所示。

N = 1021;
b = [0;0;0;0;0];
% Opens file specified by user.
fid = fopen('testing','w+'); 

% Read header data
Header = fread(fid, 140);
% Move to start of data

fseek(fid,140,'bof');

% Read from end of config header to end of file and save it in an array 
% called data
Data = fread(fid,inf);

Data=reshape(Data,N,[]);
b=repmat(b,[1 size(Data,2)]);
r=[b ; Data];
r=r(:);
r = [Header;r];
% write new values into file
fwrite(fid,r);

fclose(fid);

% Opens file specified by user.
fid = fopen('test'); 
All = fread(fid,inf);

fclose(fid); 

【问题讨论】:

    标签: file matlab file-io


    【解决方案1】:

    根据文档,w+ 选项允许您“打开或创建新文件以进行读写。丢弃现有内容,如果有的话。”文件内容被丢弃,所以DataHeader为空。

    【讨论】:

    • 我明白这一点。但是,当我从“移动到数据开始”中注释掉时,我要做的就是从文件中读取数据,它仍然没有读取任何数据,这是为什么?它会在读取数据之前先丢弃所有数据吗?
    • fopen(...,'w+') 删除内容。这是文档中描述的行为,并且经常以这种方式使用。 (例如当前会话错误日志,用 w+ 打开,如果没有发生错误则为空)
    【解决方案2】:

    您需要在写入之前设置文件句柄的位置指示符。使用frewind(fid) 可以将其设置为文件的开头,否则将文件写入/追加到当前位置。

    N = 1021;
    b = [0;0;0;0;0];
    % Opens file specified by user.
    fid = fopen('testing','r+'); 
    
    % Read header data
    Header = fread(fid, 140);
    % Move to start of data
    
    fseek(fid,140,'bof');
    
    % Read from end of config header to end of file and save it in an array 
    % called data
    Data = fread(fid,inf);
    
    Data=reshape(Data,N,[]);
    b=repmat(b,[1 size(Data,2)]);
    r=[b ; Data];
    r=r(:);
    r = [Header;r];
    % write new values into file
    frewind(fid);
    fwrite(fid,r);
    
    fclose(fid);
    
    % Opens file specified by user.
    fid = fopen('test'); 
    All = fread(fid,inf);
    
    fclose(fid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-17
      • 2016-10-26
      • 1970-01-01
      • 2013-02-06
      • 2015-09-17
      • 2012-03-04
      • 2010-10-05
      • 1970-01-01
      相关资源
      最近更新 更多