Refactored file reading into finction.

This commit is contained in:
Heiko Reese
2021-09-08 03:34:12 +02:00
parent a82f6d388b
commit 0b01283cd9
3 changed files with 81 additions and 49 deletions

53
src/common.c Normal file
View File

@ -0,0 +1,53 @@
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "common.h"
char * read_first_line(const char * filename) {
int fd;
char *endptr;
char *cipherstring;
// open file
fd = open(filename, O_RDONLY, (mode_t)0600);
if (fd == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
// get length
struct stat fileInfo = {0};
if (fstat(fd, &fileInfo) == -1) {
perror("Error getting the file size");
exit(EXIT_FAILURE);
}
if (fileInfo.st_size == 0) {
fprintf(stderr, "Error: File is empty, nothing to do\n");
exit(EXIT_FAILURE);
}
// mmap file
char *map = mmap(0, fileInfo.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
{
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
// find first line
endptr = strchrnul(map, 0x0a);
size_t cipherstring_len = endptr - map;
cipherstring = malloc(cipherstring_len+1);
strncpy(cipherstring, map, cipherstring_len);
// munmap and close file
if (munmap(map, fileInfo.st_size) == -1)
{
close(fd);
perror("Error un-mmapping the file");
exit(EXIT_FAILURE);
}
close(fd);
return cipherstring;
}