开发者

Modifying notepad text

开发者 https://www.devze.com 2023-02-14 00:09 出处:网络
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\')

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')
 fprint开发者_开发知识库f(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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号