-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrev_bytes.c
More file actions
71 lines (60 loc) · 1023 Bytes
/
rev_bytes.c
File metadata and controls
71 lines (60 loc) · 1023 Bytes
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
/* Reverse the bytes of a file. */
#include <stdio.h>
#include <stdlib.h>
#define NELEMS(arr) (sizeof(arr)) / (sizeof(arr[0]))
size_t get_fsize (FILE *f)
{
size_t n = 0, c;
rewind (f);
while (!feof (f))
{
c = getc (f);
if (-1 != c)
{
++n;
}
}
rewind (f);
return n;
}
int main (void)
{
FILE *startp;
int c;
int i;
char *bytes;
size_t fsize;
startp = fopen ("filea", "r+");
if (NULL == startp)
{
perror ("fopen");
return -1;
}
fsize = get_fsize (startp);
bytes = (char *) malloc (fsize);
if (NULL == bytes)
{
perror ("malloc");
return -1;
}
/* save the bytes in an array */
i = 0;
while (!feof (startp))
{
c = bytes[i] = getc (startp);
if (-1 != c)
{
++i;
/* printf ("%o ", c); */
}
}
/* write the reversed bytes in place */
rewind (startp);
for (i = NELEMS (bytes) - 1; i >= 0; --i)
{
fputc (bytes[i], startp);
}
free (bytes);
fclose (startp);
return 0;
}