rtc
rtc

Reputation: 69

Is there an opposite of read() in perl, like fwrite() in C?

In perl, it is possible to do a buffered read on a file with the read function, like C's fread(). However, the write function in perl "is not the opposite of read. Unfortunately", but "is used to write formatted records to file" (http://www.perlfect.com/articles/perlfile.shtml). That link suggest to use print instead. However, unlike read and fwrite() in C, which return the number of items read/written, print only returns a boolean which says whether the output was successful (https://perldoc.perl.org/functions/print.html).

Or is the result of C's fwrite() useless anyway, because part may have been written to the buffer successfully, but not yet actually flushed to the file? That seems to be an asymmetry compared to perl's read and C's fread(), which guarantee that the number of items returned were actually successfully read from the file into the buffer. So fwrite()'s return value is not reliable if it reports that all items have been successfully written. On the other hand one may argue that the return value is at least useful if it reports a short write, since in that case an error must have occurred while actually attempting to flush to the file, and so one knows for sure that the number of items reported, though short, were actually written to the file successfully.

Upvotes: 1

Views: 446

Answers (1)

Gilbert
Gilbert

Reputation: 3776

syswrite(), and sysread(), are about as close as you are going to get. These functions use write(2) and read(2) under the hood.

The argument signatures are like C's read()/write() functions in that they deal with raw bytes, not n elements of a known size.

Standard Caution: do not mix perl's normal formatted I/O with sysread()/syswrite() on the same handle unless you are into pain or deep magic.

Upvotes: 1

Related Questions