You read a value, size_buffer, and assign it to size and new_file_size, you also create a buffer[size]
of that same size,
int size = atoi(size_buffer);
sscanf(current_header.ar_fmag, "%s", fmag_buffer);
//...
new_file_size = atoi(size_buffer);
//...
char buff[size];
Read returns a ssize_t count of bytes in range [0..new_file_size]
, which you set into io_size, realize that read(2) may return < new_file_size
bytes, which is why you need the while loop. So you need to write everything you have read, until you reach your write limit. I have made some comments to guide you.
// from copy.c
while ((io_size = read (fd, buff, new_file_size)) > 0)
{
read_cntr++;
//perhaps you mean read_cntr += io_size;
//you probably mean to write io_size bytes here, regardless
//write(new_file_fd, buff, io_size);
if (read_cntr > new_file_size) //probably you want >= here
break;
//you may have broke before you write...
write (new_file_fd, buff, new_file_size);
}
A more typical idiom for this copy would be something where you pick a read/write buffer size, say 4*1024 (4K)
, 16*1024 (16K)
, etc, and read that blocksize, until you have less than that blocksize remaining; for example,
//decide how big to make buffer for read()
#define BUFSIZE (16*1024) //16K
//you need min(
#define min(x,y) ( ((x)<(y)) ? (x) : (y) )
ssize_t fdreader(int fd, int ofd, ssize_t new_file_size )
{
ssize_t remaining = new_file_size;
ssize_t readtotal = 0;
ssize_t readcount;
unsigned char buffer[BUFSIZE];
for( ; readcount=read(fd,buffer,min(sizeof(buffer),remaining)); )
{
readtotal += readcount;
if( readcount > remaining ) //only keep remaining
readcount = remaining;
write( ofd, buffer, readcount);
remaining -= readcount;
if( remaining <= 0 ) break; //done
}
return readtotal;
}
Try this,
#include<stdio.h>
#include<stdlib.h>
void usage(char*progname)
{
printf("need 2 files\n");
printf("%s <infile> <outfile>\n",progname);
}
//decide how big to make buffer for read()
#define BUFSIZE (16*1024) //16K
//you need min(
#define min(x,y) ( ((x)<(y)) ? (x) : (y) )
ssize_t fdreader(int fd, int ofd, ssize_t new_file_size )
{
ssize_t remaining = new_file_size;
ssize_t readtotal = 0;
ssize_t readcount;
unsigned char buffer[BUFSIZE];
for( ; readcount=read(fd,buffer,min(sizeof(buffer),remaining)); )
{
readtotal += readcount;
if( readcount > remaining ) //only keep remaining
readcount = remaining;
write( ofd, buffer, readcount);
remaining -= readcount;
if( remaining <= 0 ) break; //done
}
return readtotal;
}
int main(int argc,char**argv)
{
int i=0; /* the infamous 'i' */
FILE*infh;
FILE*outfh;
if( argc < 3 )
{
usage(argv[0]);
return 0;
}
printf("%s %s\n",argv[1],argv[2]); fflush(stdout);
if( !(infh=fopen(argv[1],"r")) )
{
printf("cannot open %s\n",argv[2]); fflush(stdout);
return(2);
}
if( !(outfh=fopen(argv[2],"w+")) )
{
printf("cannot open %s\n",argv[3]); fflush(stdout);
return(3);
}
int x = fdreader(fileno(infh), fileno(outfh), 512 );
return 0;
}