How to read the third line of a .txt file starting in the middle of the line?

3 views (last 30 days)
I have a text file containing student information in the following format:
School: xxxx
Grade: xxx
Student Name: LAST, FIRST
I want to read the third line and save the student last and first names as separate structure arrays formatted as Student.Name.Last and Student.Name.First
I am struggling to read exclusively the third line but only start as where the last name begins and then stop reading at the comma between the first and last name. My code currently returns the entire third line in the txt file.
fid = fopen('MyFile.txt');
linenum = 3;
C = textscan(fid,'s',1,'delimiter','\n', 'headerlines',linenum-1);
fclose(fid);

Accepted Answer

Walter Roberson
Walter Roberson on 4 Nov 2022
Edited: Walter Roberson on 4 Nov 2022
You cannot start reading in the middle of a line (except in the case that you happen to know exactly how many bytes it is from the beginning of the file, or how many bytes from whereever you are currently positioned in the file.)
Try
C = textscan(fid,'Student Name: %s,%s', 1, 'delimiter', ',', 'headerlines',linenum-1);
Possibly you will instead need
C = textscan(fid,'Student Name: %s%s', 1, 'delimiter', ',', 'headerlines',linenum-1);

More Answers (0)

Categories

Find more on Characters and Strings 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!