fgets

Reads one line from a file and keeps the newline character.

Category: Data Import and Analysis > Data Import and Export

Syntax

tline = fgets(fid)

Returns the next line including its terminator.

Description

fgets is the same as fgetl except that the line terminator stays in the result, so the length of the text tells you whether the last line ended with a newline. This matters when you are copying data byte for byte.

Input arguments

fid
File identifier from fopen.

Output arguments

tline
Character vector with the line, or -1 at the end of the file.

Example

Newline kept

fid = fopen('h.txt', 'w');
fprintf(fid, 'abc\n');
fclose(fid);
fid = fopen('h.txt');
s = fgets(fid);
fclose(fid);
numel(s)
double(s(end))
Output
ans = 4
ans = 10

See also

fgetl fopen feof fread