FWRITE()
functions directly return the number of objects processed rather than return the value in an argument.
#include <stdio.h>
#include <stddef.h>
#include <errno.h>
#define BUFFER_SIZE 256
int main(int argc, char *argv[])
{
FILE *inFile = NULL;
FILE *outFile = NULL;
size_t bytesIn, bytesOut;
char received[BUFFER_SIZE];
if(argc != 3){
printf("Usage: copyFile source, destination\n");
return 1;
}
inFile = fopen(argv[1], "rb");
if (inFile == NULL){
perror(argv[1]);
return 2;
}
outFile = fopen(argv[2], "wb");
if (outFile == NULL){
perror(argv[2]);
return 3;
}
//process input file a record at a time.
while ((bytesIn = fread(received, 1, BUFFER_SIZE, inFile)) > 0){ //the 1 represents the size of each item to be read (or written), in bytes
bytesOut = fwrite(received, 1, bytesIn, outFile);
if(bytesOut != bytesIn){
perror("Fatal write error.");
return 4;
}
}
fclose(inFile);
fclose(outFile);
return 0;
}
* fread(rec, 1, BUFFER_SIZE, inFile)
- received: The buffer where the data read from the file will be stored.
- 1: Means "read 1 byte at a time"
- BUFFER_SIZE: Means "read up to BUFFER_SIZE such 1-byte items".
- size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
- size: The size of each item (or "record") to be read/written, in bytes. This is the 1 in the code.
- nmemb: The maximum number of items (each of size size) to read/write. This is BUFFER_SIZE in the code.
* fwrite(rec, 1, bytesIn, outFile)
- received: The buffer containing the data to write to the file.
- 1: Means "write 1 byte at a time".
- bytesIn: Means "write bytesIn such 1-byte items" (which is the number of bytes successfully read from the input file in the previous fread call).
- size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
- size: The size of each item (or "record") to be read/written, in bytes. This is the 1 in the code.
- nmemb: The maximum number of items (each of size size) to read/write. This is BUFFER_SIZE in the code.
Last updated