MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   在Matlab中写入文件时从EOF中删除字符 (https://www.labfans.com/bbs/showthread.php?t=22880)

poster 2019-12-10 16:49

在Matlab中写入文件时从EOF中删除字符
 
在Matlab中,创建一定数量的行并将其打印到文件后,我需要删除一行并将其余数据重写为该文件。当我这样做时,新数据将覆盖先前的数据,但是由于该数据比原始数据短,因此仍然有原始数据的残留。有谁知道删除多余数据的最佳/最有效方法是什么?

这是我要执行的操作的简化示例:

fid = fopen('file.txt','w'); for i=1:10 fprintf(fid,'%i\r\t',i); end frewind(fid); for i=3:5 fprintf(fid,'%i\r\t',i); end fprintf(fid,'EOF'); fclose(fid); 我已经看了很多遍,但似乎找不到解决我问题的方法。有什么建议么?


回答:
不使用任何临时文件,您可以执行以下操作:

fid = fopen('file.txt', 'wt'); for i=1:10 fprintf(fid, '%i\n', i); end frewind(fid); for i=3:5 fprintf(fid, '%i\n', i); end pos = ftell(fid); % get current position in file fclose(fid); % read from begining to pos fid = fopen('file.txt', 'r'); data = fread(fid, pos); fclose(fid); % overwite file with data read fid = fopen('file.txt', 'w'); fwrite(fid, data); fclose(fid);

[url=https://stackoverflow.com/questions/1690962]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 20:45

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.