文件复制函数
时间:2010-05-18 来源:asteriskchina
static int copy(const char *infile, const char *outfile)
{
int ifd, ofd, len;
char buf[4096]; /* XXX make it lerger. */
if ((ifd = open(infile, O_RDONLY)) < 0) { ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile); return -1; } if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) { ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile); close(ifd); return -1; } while ( (len = read(ifd, buf, sizeof(buf)) ) ) { int res; if (len < 0) { ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno)); break; } /* XXX handle partial writes */ res = write(ofd, buf, len); if (res != len) { ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno)); len = -1; /* error marker */ break; } } close(ifd); close(ofd); if (len < 0) { unlink(outfile); return -1; /* error */ } return 0; /* success */ }
if ((ifd = open(infile, O_RDONLY)) < 0) { ast_log(LOG_WARNING, "Unable to open %s in read-only mode\n", infile); return -1; } if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, 0600)) < 0) { ast_log(LOG_WARNING, "Unable to open %s in write-only mode\n", outfile); close(ifd); return -1; } while ( (len = read(ifd, buf, sizeof(buf)) ) ) { int res; if (len < 0) { ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno)); break; } /* XXX handle partial writes */ res = write(ofd, buf, len); if (res != len) { ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno)); len = -1; /* error marker */ break; } } close(ifd); close(ofd); if (len < 0) { unlink(outfile); return -1; /* error */ } return 0; /* success */ }
相关阅读 更多 +