MATLAB: Low level IO: How to remove trailing new line at the very end

newline

My code is in the attached.
When I create my new textfile, there is always that trailing newline at the last line which I do not want. This is what the solution text file looks like:
Text
Text
Text
However, this is what my textfile looks like
Text
Text
Text
Empty New Line
I know there has to be some while loop or if statement that I should be using but I can't figure it out (nor where to put it in my code). Was wondering if anyone could help. thank you.

Best Answer

Do these things:
  • use fopen with the text option, e.g. 'rt'.
  • use fgetl isntead of fgets.
  • use feof instead of testing if the output is char.
  • use sprintf instead of string concatenation.
  • use frewind instead of repeatedly opening and closing files.
  • redefine the format string at the end of the while loop (see fmt below).
For example:
function mashUp(text1, text2, list)
%Summary: Combine the lyrics of two songs into a new textfile.
fh1 = fopen(text1,'rt');
fh2 = fopen(text2,'rt');
fh3 = fopen(list,'rt');
[texter1, ~] = strtok(text1, '.');
[texter2, ~] = strtok(text2, '.');
newName = sprintf('%s_%s_mashUp.txt',texter1,texter2);
fhw = fopen(newName,'wt');
fmt = '%s';
while ~feof(fh3)
line3 = fgetl(fh3);
[token1,rest1] = strtok(line3,'-');
rest1(1) = [];
token1 = str2double(token1);
rest1 = str2double(rest1);
if token1 == 1 %File 1 printing
tmp = fh1;
elseif token1 == 2 %File 2 printing
tmp = fh2;
end
placeHolder = ones(1, rest1);
for idx = placeHolder
line = fgetl(tmp);
end
frewind(tmp)
fprintf(fhw,fmt,line);
fmt = '\n%s';
end
fclose(fh1)
fclose(fh2)
fclose(fh3)
fclose(fhw)
end