return value of gets command

189 Views Asked by At

what does the return value of gets command in following exercise means?

I tried to read file by tclsh on command line.

File

           10      2       12      1       13
1       2       3       4       5        6
1       2       3       4       5
1       2       3       4a       5

Command & Output (command-line)

% set fp [open file r]
file4
% gets $fp line
45
%  gets $fp line
42
%  gets $fp line
41
%  gets $fp line
42
%  gets $fp line
-1
% close $fp

when I got -1 output I closed the file-pointer $fp. but what does the values 45 42 41 42 meant?

1

There are 1 best solutions below

1
On BEST ANSWER

Quoting from the man page of gets command

Syntax :

gets channelId ?varName?

This command reads the next line from channelId, returns everything in the line up to (but not including) the end-of-line character(s), and discards the end-of-line character(s).

If varName is specified and an empty string is returned in varName because of end-of-file or because of insufficient data in nonblocking mode, then the return count is -1.

If varName is omitted the line is returned as the result of the command. If varName is specified then the line is placed in the variable by that name and the return value is a count of the number of characters returned.

As you can see from the man page, it returns the count of characters which is read by gets command in one single line. In the first line of the file, it read 45 characters and returned 45 as a result and the string value will be stored in the variable line as per your code.

This is repeated for all lines and will return -1 once the eof reached for that file.