Skip to content

Instantly share code, notes, and snippets.

@theasder
Last active December 23, 2015 20:19
Show Gist options
  • Save theasder/6688846 to your computer and use it in GitHub Desktop.
Save theasder/6688846 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define SIZE 12
#pragma pack(1)
struct Data
{
int x;
long long y;
};
void readbyte(int f, void *p, unsigned int size) {
int i, status;
unsigned char* ptr = p;
for(i = 0; i < size; i++) {
status = -1;
while(status != 1)
status = read(f, ptr, 1);
ptr++;
}
return;
}
void rdstrct(int* fd, int* x, long long int* y)
{
readbyte(*fd, x, 4);
readbyte(*fd, y, 8);
return;
}
void writebyte(int f, void *p, unsigned int size) {
int i, status;
unsigned char* ptr = p;
for(i = 0; i < size; i++) {
status = -1;
while(status != 1)
status = write(f, ptr, 1);
if(status == -1) return -1;
ptr++;
}
return 0;
}
int wrstrct(int* fd, int* x, long long int* y)
{
int n;
writebyte(*fd, x, 4);
writebyte(*fd, y, 8);
return 0;
}
int main(int argc, char* argv[])
{
int A = atoi(argv[2]);
int fd, fd_end, i;
int x, x2, n;
long long y, y2;
if((fd = open(argv[1], O_RDWR)) == -1)
return -1;
// finding size of the file
fd_end = fd;
long long int n1 = lseek(fd, 0L, SEEK_SET);
long long int n2 = lseek(fd_end, 0L, SEEK_END);
long long int sz = n2 - n1;
printf("%lld\n", sz);
for(i = 1; i <= sz / 24; i++ )
{
lseek(fd_end, sz - i * 12, SEEK_SET);
rdstrct(&fd_end, &x, &y);
y += x * A;
lseek(fd, (i - 1) * 12, SEEK_SET);
rdstrct(&fd, &x2, &y2);
y2 += x2 * A;
lseek(fd, (i - 1) * 12, SEEK_SET);
n = wrstrct(&fd, &x, &y);
if(n == -1) return -1;
lseek(fd_end, sz - i * 12, SEEK_SET);
n = wrstrct(&fd_end, &x2, &y2);
if(n == -1) return -1;
}
if(sz % 24 != 0)
{
lseek(fd, (sz / 24) * 12, SEEK_SET);
rdstrct(&fd, &x2, &y2);
y2 += x2 * A;
lseek(fd, (sz / 24) * 12, SEEK_SET);
n = wrstrct(&fd, &x2, &y2);
if(n == -1) return -1;
}
close(fd);
return 0;
}
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#pragma pack(1)
struct Data
{
int x;
long long y;
};
int main(int argc, char** argv)
{
int fd, fp, i;
struct Data arr[] = {
1, 2,
3, 4,
5, 6,
};
struct Data *buf = (struct Data *)malloc(12);
fd = creat(argv[1], 0777);
for(i = 0; i < 3; i++) {
printf("%d %lld\n", arr[i].x, arr[i].y);
write(fd, &arr[i], 12);
}
close(fd);
fp = open(argv[1], O_RDONLY);
for(i = 0; i < 3; i++) {
read(fp, buf, 12);
printf("%d %lld\n", buf -> x, buf -> y);
}
close(fp);
free(buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment