Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Created August 29, 2020 10:19
Show Gist options
  • Save cs-fedy/b36dcb2d4182a606b100ed619f173902 to your computer and use it in GitHub Desktop.
Save cs-fedy/b36dcb2d4182a606b100ed619f173902 to your computer and use it in GitHub Desktop.
copy file content using posix in C.
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#define NMAX 100
int main(int argc, char **argv) {
int src, dist, nb;
char buffer[NMAX];
/*** testing arguments ***/
if (argc <3) {
fprintf(stderr, "usage %s source destination \n", argv[0]);
exit(EXIT_FAILURE);
}
/*** opening source file on read mode ***/
src = open(argv[1], O_RDONLY);
if (src == -1) {
perror("error while opening source file");
exit(EXIT_FAILURE);
}
/*** opening distination file on writing mode ***/
/*** O_WRONLY, creates a file if doesn't exist and open it on writing mode ***/
/*** O_CREAT, if the file exist delete everything in it using O_TRUNC ***/
dist = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dist == -1) {
perror("error while opening destination file");
exit(EXIT_FAILURE);
}
while (nb = read(src, buffer, NMAX) > 0) {
if (write(dist, buffer, NMAX) > -1) {
return -1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment