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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void revert(char* beg, char* end)
{
while (beg < end) {
char tmp = *--end;
*end = *beg;
*beg++ = tmp;
}
}
int main(int argc, char** argv)
{
FILE *in = NULL, *out;
size_t allocated = BUFSIZ, rd = 0, sz;
char *buffer = malloc(allocated), *ptr1, *ptr2;
int status = EXIT_FAILURE;
if (buffer == NULL)
goto bye;
if (!(argc == 3 && (in = fopen(argv[1], "r")) && (out = fopen(argv[2], "w"))))
if (in) goto closein; else goto bye;
while ( (sz = fread(buffer+rd, 1, allocated-rd, in)) != 0) {
rd += sz;
if (rd == allocated) {
char* newbuf = realloc(buffer, allocated+allocated/2);
if (newbuf == NULL) {
rd -= allocated/2;
memmove(buffer, buffer+allocated/2, rd);
} else {
allocated += allocated/2;
buffer = newbuf;
}
}
}
ptr1 = buffer;
revert(ptr1, buffer+rd);
while ( (ptr2 = memchr(ptr1, '\n', buffer + rd - ptr1)) != NULL) {
revert(ptr1, ptr2);
ptr1 = ptr2+1;
}
revert(ptr1, buffer+rd);
if (fwrite(buffer, 1, rd, out) == rd)
status = EXIT_SUCCESS;
closeout:
fclose(out);
closein:
fclose(in);
free(buffer);
bye:
return status;
} |
Partager