Skip to content

Instantly share code, notes, and snippets.

@oraoto
Created December 28, 2017 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oraoto/d76ebf699ed1cb86faae02bc6246ff0e to your computer and use it in GitHub Desktop.
Save oraoto/d76ebf699ed1cb86faae02bc6246ff0e to your computer and use it in GitHub Desktop.
Romove BOM wih copy_file_range
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
static loff_t
copy_file_range(int fd_in, loff_t *off_in, int fd_out,
loff_t *off_out, size_t len, unsigned int flags)
{
return syscall(__NR_copy_file_range, fd_in, off_in, fd_out,
off_out, len, flags);
}
int
main(int argc, char **argv)
{
int fd_in, fd_out;
struct stat stat;
loff_t len, ret;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
fd_in = open(argv[1], O_RDONLY);
if (fd_in == -1) {
perror("open (argv[1])");
exit(EXIT_FAILURE);
}
if (fstat(fd_in, &stat) == -1) {
perror("fstat");
exit(EXIT_FAILURE);
}
len = stat.st_size;
lseek(fd_in, 3, SEEK_SET);
char template[] = ".XXXXXX";
char * temp_file = mktemp(template);
fd_out = open(temp_file, O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd_out == -1) {
perror("open (argv[2])");
exit(EXIT_FAILURE);
}
do {
ret = copy_file_range(fd_in, NULL, fd_out, NULL, len, 0);
if (ret == -1) {
perror("copy_file_range");
exit(EXIT_FAILURE);
}
len -= ret;
} while (len > 3);
close(fd_in);
close(fd_out);
rename(temp_file, argv[1]);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment