Skip to content

Instantly share code, notes, and snippets.

@chadrehm
Last active March 13, 2021 19:18
Show Gist options
  • Select an option

  • Save chadrehm/c4ec697c16ba2f20d0e039bdc6c01549 to your computer and use it in GitHub Desktop.

Select an option

Save chadrehm/c4ec697c16ba2f20d0e039bdc6c01549 to your computer and use it in GitHub Desktop.
C program to learn posix function. Copy a file.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define BUFFER_SIZE 256
void handleError(char* message, char* secondMessage, int checkNum);
int main(int argc, char** argv)
{
int readfd,
writefd,
rcount,
wcount,
totalByte = 0,
closeRead,
closeWrite,
xid;
char buffer[BUFFER_SIZE];
// confirm that the correct number of arguments were passed.
if (argc < 3 || argc > 3 ) {
printf("filecopy: invalid number of arguments\n");
printf("usage: filecopy <sourcefile> <destinationfile>\n");
return 1;
}
// Opens a designated file for reading
readfd = open(argv[1], O_RDONLY, 0);
// Error if file didn't open
handleError("Unable to open", argv[1], readfd);
// Creates a new file named, sets read/write permissions for user
// and read permissions for group and other
writefd = creat(argv[2], S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
// Error if file create failed
handleError("Unable to create", argv[2], writefd);
do {
// Read up to BUFFER_SIZE bytes from the file into the buffer.
rcount = read(readfd, buffer, BUFFER_SIZE);
// Error if read failed
handleError("Unable to read", "data", rcount);
// No more data found exit loop
if (rcount == 0) {
break;
}
// Write to a file the contents of buffer, up to rcount number of bytes
wcount = write(writefd, buffer, rcount);
// Error if write failed
handleError("Unable to write to", argv[2], wcount);
// Tally total count for output
totalByte = totalByte + wcount;
} while(rcount != 0);
// Close output file
closeWrite = close(writefd);
// Error closing write file
handleError("Unable to close", argv[2], closeWrite);
// Close input file
closeRead = close(readfd);
// Error closing input file
handleError("Unable to close", argv[1], closeRead);
printf("copied %d bytes from file %s to %s\n", totalByte, argv[1], argv[2]);
return 0;
}
void handleError(char* message, char* secondMessage, int checkNum) {
if (checkNum == -1) {
printf("%s %s: %s\n", message, secondMessage, strerror( errno ));
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment