File input/output: Difference between revisions

→‎{{header|C}}: buf size, file mode, etc.
(→‎{{header|Ruby}}: Show FileUtils.copy_file, FileUtils.copy_stream, a copy loop, and IO.copy_stream. There are now 6 ways to copy a file.)
(→‎{{header|C}}: buf size, file mode, etc.)
Line 217:
A couple of remarks on the preceding example:
 
It uses <ttcode>fgetc</ttcode> to read one character at a time. Each character is visited, even though there's nothing to do with it. Copying bigger blocks of data is much more efficient.
 
The following example addresses those issues. To avoid buffered IO, it uses ''open()'', ''read()'', ''write()'' and ''close()'', which are part of [[POSIX]], but not defined of [[ANSI C]].
It uses buffered IO to perform the move, which is overkill. This is not actually a weakness, but it invokes some overhead that you don't need.
 
The following example addresses those issues. To avoid buffered IO, it uses ''open()'', ''read()'', ''write()'' and ''close()'', which are part of [[POSIX]], but not defined of [[ANSI C]].
 
{{works with|POSIX}}
<lang c>#include <stdiounistd.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistdsys/stat.h>
 
/* we just return a yes/no status; caller can check errno */
int maincopy_file(intchar argc*in, char **argvout)
{
int ret = len0;
{ int fifin, fofout;
ssize_t len;
char *buf[4096]; /* buffer size, some multiple of block size preferred */
struct stat st;
 
if ((fifin = open("input.txt"in, O_RDONLY)) <== 0-1) {return 0;
int main(int argc, char **argv)
if (fstat(fin, &st)) goto bail;
{ int fi, fo;
int len;
char buf[1024]; /* a better choice is the FS block size, if you know it */
 
/* open output with same permission */
if ((fi = open("input.txt", O_RDONLY)) < 0) {
fout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);
perror("Can't read input.txt");
if (fout == -1) returngoto 1bail;
}
 
if while ((folen = openread("output.txt"fin, O_WRONLY|O_CREAT|O_TRUNCbuf, 4096)) <> 0) {
if ( write(fofout, buf, len) < 0) {;
perror("Can't write to output.txt");
return 1;
}
 
ret = while ((len =? read(fi,0 buf,: 1; /* last read 1024))should >be 0) {*/
if (write(fo, buf, len) < 0) {
perror("write failed");
return 1;
}
}
 
bail: if (lenfin <!= 0-1) { close(fin);
if (fout != -1) close(fout);
perror("read failed");
return 1ret;
}
 
int main()
close(fi); close(fo);
{
return 0;
copy_file("infile", "outfile");
return 10;
}</lang>
 
Anonymous user