Skip to content

Instantly share code, notes, and snippets.

@theasder
Created October 22, 2013 19:24
Show Gist options
  • Save theasder/7106619 to your computer and use it in GitHub Desktop.
Save theasder/7106619 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
int main(void)
{
int bytes = 0, end, i, displacement = 0, old_displacement = 0;
struct stat *buf = malloc(sizeof(struct stat));
lstat("input.dat", buf);
unsigned int size = buf -> st_size;
printf("size = %d\n", size);
free(buf);
int fd = open("input.dat", O_RDWR);
char buf_int[4] = {0}, buf_short[2] = {0}, buf_char;
while(1){
end = read(fd, &bytes, 1); // reading first byte
if(end == 0) break; // if it is the end let's get out
if(bytes == 1) {
end = read(fd, &buf_char, 1); // if we have read only one byte than let's go on
printf("readed %x\n", buf_char);
lseek(fd, -old_displacement - 3, SEEK_CUR);
write(fd, &bytes, 1);
write(fd, &buf_char, 1);
printf("writed %x\n", buf_char);
lseek(fd, displacement, SEEK_CUR);
continue;
}
printf("bytes = %d\n", bytes);
printf("displacement = %d\n", old_displacement);
if(bytes == 4) {
for(i = 0; i < 4; i++) {
read(fd, &buf_int[i], 1); // reading entire 4-byte integer
printf("readed buf_int[%d] = %x\n", i, buf_int[i]);
}
old_displacement = displacement;
if(buf_int[1] == 0 && buf_int[2] == 0 && buf_int[3] == 0) {
bytes = 1; // if we have zeros in three damn bytes than
displacement += 3; // adding 3 to displacement to omit zeros
}
else if(buf_int[2] == 0 && buf_int[3] == 0) {
bytes = 2;
displacement += 2; // the same
}
else if(buf_int[1] == ~0 && buf_int[2] == ~0 && buf_int[3] == ~0 && buf_int[0] >> 3)
{
bytes = 1;
displacement += 3;
}
else if(buf_int[2] == ~0 && buf_int[3] == ~0 && buf_int[1] >> 3){
bytes = 2;
displacement += 3;
}
lseek(fd, -old_displacement - 5, SEEK_CUR); // let's make displacement from *already readed*
// to the start
write(fd, &bytes, 1); // rewriting the indicator byte
for(i = 0; i < bytes; i++) {
write(fd, &buf_int[i], 1);
printf("writed buf_int[%d] = %x\n", i, buf_int[i]);
}
// lseek(fd, displacement, SEEK_CUR);
printf("displacement = %d\n", displacement);
lseek(fd, displacement, SEEK_CUR);
continue;
}
if(bytes == 2) {
for(i = 0; i < 2; i++) {
read(fd, &buf_short[i], 1);
printf("readed buf_short[%d] = %x\n", i, buf_short[i]);
}
old_displacement = displacement;
if(buf_short[1] == 0) {
bytes = 1;
displacement += 1;
}
else if(buf_short[1] == ~0 && buf_short[0] >> 3) {
bytes = 1;
displacement += 1;
}
lseek(fd, -old_displacement - 3, SEEK_CUR);
write(fd, &bytes, 1);
for(i = 0; i < bytes; i++) {
write(fd, &buf_short[i], 1);
printf("writed buf_short[%d] = %x\n", i, buf_short[i]);
}
lseek(fd, displacement, SEEK_CUR);
}
}
close(fd);
truncate("input.dat", size - displacement);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment