File: utils.c

package info (click to toggle)
recoverdm 0.20-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 252 kB
  • sloc: ansic: 2,503; makefile: 45; sh: 14
file content (79 lines) | stat: -rw-r--r-- 1,760 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#define _LARGEFILE64_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "io.h"
#include "dev.h"
#include "gen.h"
#include "utils.h"
#include "error.h"

void * mymalloc(size_t size, char *what)
{
	void *dummy = malloc(size);
	if (!dummy)
		error_exit("failed to allocate %d bytes for %s\n", size, what);

	return dummy;
}

void * myrealloc(void *oldp, size_t newsize, char *what)
{
	void *dummy = realloc(oldp, newsize);
	if (!dummy)
		error_exit("failed to reallocate to %d bytes for %s\n", newsize, what);

	return dummy;
}

off64_t get_filesize(char *filename)
{
	struct stat64 finfo;

	if (stat64(filename, &finfo) == -1)
		error_exit("Failed to retrieve length of file %s: %s (%d)\n", filename, strerror(errno), errno);

	return finfo.st_size;
}

int copy_block(int fd_in, int fd_out, off64_t block_size)
{
	char buffer[512];

	while (block_size > 0)
	{
		size_t sector_size = min(block_size, 512);

		/* read from inputfile */
		if (READ(fd_in, buffer, sector_size) != sector_size)
		{
			fprintf(stderr, "Failed to read %d bytes from inputfile: %s (%d)\n", sector_size, strerror(errno), errno);
			return -1;
		}

		/* write to outputfile */
		if (phantom_write(fd_out, buffer, sector_size) != sector_size)
		{
			fprintf(stderr, "Failed to write to outputfile: %s (%d)\n", strerror(errno), errno);
			return -1;
		}

		/* decrease number of bytes left */
		block_size -= sector_size;
	}

	return 0;
}

void myseek(int fd, off64_t offset)
{
	/* seek in inputfile to correct offset */
	if (lseek64(fd, offset, SEEK_SET) == -1)
		error_exit("Failed to seek in file to offset %lld: %s (%d)\n", offset, strerror(errno), errno);
}