Oracle Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
I think better use some intermediate buffer with fread/fwrite instead to minimize the number of calls to library functions
-1
too slow , it is not efficient();
unsigned int copyfile(FILE *p, FILE *q)
{
char buf[4096]={0};
int readbytes=0,writebytes=0;
int count=0;
//fseek(p,0,SEEK_SET);
while(readbytes=fread(buf,1,4096,p))
{
if((readbytes!=4096)&&(!feof(p)))
{
printf("%d",ferror(p));
return 0;
}
if(writebytes=fwrite(buf,1,readbytes,q))
{
if(writebytes!=readbytes)
{
printf("%d",ferror(q));
return 0;
}
count=count+writebytes;
}
if(readbytes!=4096) break;
}
return count;
}
}
/*
Usage: copy <infile> <outfile>
Copies infile to outfile BUFSZ bytes at a time.
Does not handle interrupted syscalls.
Exit value is 0 on success, non-zero otherwise.
Primitive error checking with assert.
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#define BUFSZ 1024
int
main(int argc, char *argv[])
{
assert(argc == 3);
int readfd = open(argv[1], O_RDONLY);
assert(readfd >= 0);
int writefd = open(argv[2], O_WRONLY|O_CREAT);
assert(writefd >= 0);
char buf[BUFSZ];
ssize_t len;
while ((len = read(readfd, buf, BUFSZ)) > 0)
if (write(writefd, buf, len) != len)
goto error;
if (len < 0)
goto error;
close(readfd);
close(writefd);
return 0;
error:
return 1;
}
void copyFile()
- Anonymous April 15, 2012{
FILE *fileSrc, *fileDest;
char c;
fileSrc = fopen("file1","ro");
fileDest = fopen("file2","w");
while((c=fgetc(fileSrc)!= EOF)
fputc(fileDest,c);
}