This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Read line from file, keeping newline characters


tline = fgets(fileID)
tline = fgets(fileID, nchar)


tline = fgets(fileID) reads the next line of the specified file, including the newline characters. fileID is an integer file identifier obtained from fopen. tline is a text string unless the line contains only the end-of-file marker. In this case, tline is the numeric value -1. fgets reads characters using the encoding scheme associated with the file. To specify the encoding scheme, use fopen.

tline = fgets(fileID, nchar) returns at most nchar characters of the next line. tline does not include any characters after the newline characters or the end-of-file marker.


Read and display the file fgets.m. Because fgets keeps newline characters and disp adds a newline character, this code displays the file with double-spacing:

fid = fopen('fgets.m');

tline = fgets(fid);
while ischar(tline)
    tline = fgets(fid);


Compare these results to the fgetl example, which replaces the calls to fgets with fgetl.

Introduced before R2006a

Was this topic helpful?