Question

I'm working on a function in MATLAB that reads input from a file. So far (after reading a bit here about scanf vulnerabilities) I decided to use fgets to get each line, and then textscan to extract the words, which will always be of the format 'chars' including the apostrophes. So, I'm using:

fid = fopen('file.txt');
tline = fgets(fid);
textscan(tline, '''%s''');

However, I want to allow people to have comments, using the % character. How do I cut off textscan so that

'word' 'anotherword' % 'comment'

doesn't return comment?

Was it helpful?

Solution

fid = fopen('file.txt');
tline = fgets(fid);
pct = find(tline=='%');
tline(pct(1)-1:end)=[]; % deletes tline from first instance of '%' onward.
textscan(tline, '''%s''');

Note that the above will cut off after any % at all in the line, even if it is in quotes.

If you want to allow the character % in your quoted string yous you have to do more logic on testing for comment % before deleting rest of tline. Look at the strcmp and findstr functions which may be useful.

OTHER TIPS

After doing some more reading around while debugging, I found a more straightforward way to do this.

textscan(tline, '''%s''', 'commentStyle', '%');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top