Arbortext Command Language > Functions by Alphabetical Listing > read (Function)
  
read (Function)
read(fid, buf, len[, re])
This function reads up to len characters from the file or channel identified by fid into the scalar variable buf. This function returns the number of characters read, or 0 at the end of the file if the channel was closed. It returns -1 if an error occurred. fid is a file identifier returned by open for reading or a network channel identifier returned by open_connect or open_accept.
If re is specified, it specifies a single character that marks the end of the record. In this case, read copies characters into buf until the re character is found and transferred into buf, or len bytes are read. If re is null character (\000) or omitted, then the data stream is not searched for a record end character.
* 
read(fid, bu, 3000, "\n") is equivalent to getline(fid, buf).
When reading from a channel in non-blocking mode (from a callback established by channel_set_callback), the read may return fewer than len bytes. The return value is the actual number of bytes read. If the read would block, that is, there is no data pending on the channel, read returns -2. read also returns -2 if re is given, but the data pending on the channel does not contain the record end character. In this case, Arbortext Editor queues the data internally until a complete record is available to return to a subsequent read from the channel callback read notification.
Unlike getline, read can handle binary data, that is, null characters. The following example is a function that can be used to make an exact copy of a file that may contain binary data. Note, that the “b” flag must be specified when opening both files.
function file_copy(from, to) {
local inf, outf
inf = open(from, "rb")
if (inf < 0) {
response("Couldn't open file for read:" . from)
return 0
}
outf = open(to, "wb")
if (outf < 0) {
close(inf)
response("Couldn't open file for write:" . to)
return 0
}
local buf, n=0, len
while ((len = read(inf, buf, 512)) > 0) {
n += write(outf, buf, len)
}
close(outf)
close(inf)
return n;
}
Related Topics
channel_set_callback built-in function
getline built-in function