Reads lines of text from a file into a string array retaining newlines.


sa = fgetsa(fh, numl)
  • fh (scalar) – file handle of a file opened with fopen().

  • numl (scalar) – number of lines to read.


sa (Nx1 string array) – Contains the text read from the file lines specified by the file handle fh. \(N <= numl\).


// Specify file name with full path
fname = getGAUSSHome("examples/housing.csv");

// Open file handle for reading
fh = fopen(fname, "r");

// Read the first 3 lines of the file
s = fgetsa(fh, 3);

After the above code, s will equal:


Note that s will be a 3x1 string array. Though the final character in each line is the newline character. So if you print the contents of s in GAUSS, you will see an empty line between each line of text.


The fgetsa() procedure reads up to numl lines of text. If fgetsa() reaches the end of the file before reading numl lines, sa will be shortened. Lines are read in the same manner as fgets(), except that no limit is placed on the size of a line. Thus, fgetsa() always returns complete lines of text with newlines retained.

If numl is 1, fgetsa() returns a string. (This is one way to read a line from a file without placing a limit on the length of the line.)

If the file is already at end-of-file when you call fgetsa(), your program will terminate with an error. Use eof() in conjunction with fgetsa() to avoid this.

If the file was opened for update (see fopen()) and you are switching from writing to reading, don’t forget to call fseek() or fflush() first, to flush the file’s buffer.

If you pass fgetsa() the handle of a file opened with open (i.e., a data set or matrix file), your program will terminate with a fatal error.

See also

Functions fgetsat(), fgets(), fopen()