修改记事本文本
我试图编写一个代码,其中:
%# Matlab reads a notepad file.
f_id=fopen('n1.txt','r');
reports=textscan(f_id, '%s', 'Delimiter', '\n')
fclose(f_id)
reports_saved=reports{1} ;
P='blah blah'
编辑:
goes to a specific line of the text file.
X=ftell(f_id)
Ai=fseek(f_id, 0, 'cof')
fprintf(f_id,'%s', P);
fclose(f_id)
第一行“cof”指针被覆盖。现在,问题 1:如果新文本比现有文本短,则覆盖后现有文本中的字符仍会保留。有任何提示为什么吗? 问题 2:“fseek”仅允许转到文件的开头、当前位置或结尾。有没有办法让指针随机移动,就像转到文本 no4 /5 一样。请注意,每个文本之间都有一个空行。
感谢任何帮助。
I've tried to write a code in which:
%# Matlab reads a notepad file.
f_id=fopen('n1.txt','r');
reports=textscan(f_id, '%s', 'Delimiter', '\n')
fclose(f_id)
reports_saved=reports{1} ;
P='blah blah'
EDIT:
goes to a specific line of the text file.
X=ftell(f_id)
Ai=fseek(f_id, 0, 'cof')
fprintf(f_id,'%s', P);
fclose(f_id)
The 1st line where 'cof' pointer was over written. Now, Problem 1: If the new text is shorter than the existing one, characters from the existing text remains after overwriting. Any hints why ? Problem 2: 'fseek' only allows to go to beginning, current position or end of the file. Is there any way to make the pointer move randomly like going to text no4 /5. Note, each text has got a blank line in between them.
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文本文件是磁盘上的一组连续字节。如果更改文件中间任何文本段的长度,则需要重写文件的所有后续字节,然后截断或扩展文件。它们不会自动移动。这就像在内存中的数组结构中插入或删除(在 C 等较低级语言中,它不会像 Matlab 那样自动调整数组大小),而不是链表。
直接使用该文件可能是错误的方法。 Matlab 甚至不提供 ftruncate() 函数,您需要在用较短的文本替换文本后缩短文件。只需将整个文件读入内存中的数组,在那里对其进行操作,然后使用 fopen(...,'w') 将整个文件写回,替换原始文件。如果您正在进行面向行的更改,那么使用 cellstr 行数组可能会比使用嵌入行分隔符的大 char 数组更容易。
A text file is a set of contiguous bytes on disk. If you change the length of any segment of text in the middle of the file, you need to rewrite all the subsequent bytes of the file, and then truncate or extend the file. They don't shift automatically. It's like inserting or deleting from an array structure in memory (in a lower-level language like C that doesn't automagically resize arrays like Matlab does), not a linked list.
Working directly with the file is probably the wrong way to do this. Matlab doesn't even provide the ftruncate() function you would need to shorten the file after replacing text with a shorter piece of text. Just read the entire file in to an array in memory, manipulate it there, and then write the entire thing back out with fopen(...,'w'), replacing the original file. If you're doing line-oriented changes, it'll probably be easier to work with a cellstr array of lines instead of one big char array with embedded line delimiters, too.
尝试使用
'r+'
打开文件。'w'
只会创建一个新文件并删除旧文件中的所有内容(如果存在)。f_id=fopen('fire.txt','r+');
Try opening the file with
'r+'
.'w'
will just create a new file and delete everything in the old one (if it exists).f_id=fopen('fire.txt','r+');