Anonymous user
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 <
The following example addresses those issues. To avoid buffered IO, it uses ''open()'', ''read()'', ''write()'' and ''close()'', which are part of [[POSIX
▲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 <
#include <unistd.h>▼
#include <fcntl.h>
#include <sys/types.h>
/* we just return a yes/no status; caller can check errno */
{
ssize_t len;
char *buf[4096]; /* buffer size, some multiple of block size preferred */
struct stat st;
▲int main(int argc, char **argv)
if (fstat(fin, &st)) goto bail;
▲{ int fi, fo;
▲ int len;
/* 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);
if (fout == -1)
return 1;▼
ret =
▲ if (write(fo, buf, len) < 0) {
if (fout != -1) close(fout);
int main()
{
copy_file("infile", "outfile");
}</lang>
|