How are you supposed to write the code returned from "grabcode" to a file?!

1 view (last 30 days)
I have lots of published files I am trying to go through and get the code for. I was so happy when I saw that the "grabcode" function returned a string with all the code in it.
My code was this: out=grabocde('myFile.html') and out was a 1x5300 char
My assumption was that this code would have all the linebreaks and whatnot in the code, and when I called disp(out), it displayed perfectly.
My next step was to save this code into a mfile so I could run it. Note that I need to do this thousands of times so opening in the editor and clicking save is not practical.
I simply did fid=fopen('myFile.m','w')
and then just tried fprintf(fid,out) and it didn't do anything, I closed the file and tried opening it and it was blank.
I then re-opened the file and tried: str='darnnn it, why wont you just work'; fprintf(fid,str) and it worked fine.
I closed the file and tried to do grabcode on a different mfile, this time it grabbed the entire first line and then gave me an error about an invalid escape sequence "M" and was done. The other file gave no errors.
And that is pretty much where I am at. I think I do not understand the different ways of having text info in MATLAB, but if somebody could enlighten me, that would be great!

Accepted Answer

Sean de Wolski
Sean de Wolski on 20 Feb 2013
Edited: Sean de Wolski on 20 Feb 2013
Two easy ways:
You can use the traditional, and probably better, trifecta of fopen/fprintf/fclose
fid = fopen('test2.m','w');
fprintf(fid,'Hello\nWorld'); %your text
fclose(fid);
Or use the editor API:
matlab.desktop.editor.newDocument; %New document
hEditor = matlab.desktop.editor.getActive; %grab the handle to the new document
hEditor.insertTextAtPositionInLine(sprintf('Hello\nWorld'),1,1); %replace sprintf with output from grabcode
hEditor.saveAs([pwd filesep 'test.m']); %save it as whatever

More Answers (1)

Shaun VanWeelden
Shaun VanWeelden on 20 Feb 2013
The problem I was having is that all % signs, and well probably ! signs and other escape characters need to be changed for the fprintf to read it properly.

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!