Skip to content

Instantly share code, notes, and snippets.

@Sebbyastian
Last active November 14, 2015 14:01
Show Gist options
  • Save Sebbyastian/9b73e7337daf6cf04b17 to your computer and use it in GitHub Desktop.
Save Sebbyastian/9b73e7337daf6cf04b17 to your computer and use it in GitHub Desktop.
finsert, a function to insert data into the middle of a file...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int finsert(FILE *file, fpos_t position, void *object, size_t size) {
unsigned char i[size], o[size];
memcpy(o, object, size);
if (fsetpos(file, &position)) {
return -1;
}
while (size > 0) {
size_t x = fread(i, 1, size, file);
if (fsetpos(file, &position) || fwrite(o, 1, size, file) < size
|| fflush(file)
|| fgetpos(file, &position)) {
return -1;
}
size = x;
memcpy(o, i, size);
}
return 0;
}
int main(int argc, char **argv) {
if (argc <= 3) {
puts("Usage: ./app filename position data");
return 0;
}
FILE *file = fopen(argv[1], "rb+");
if (file == NULL) {
puts("Error opening file...");
return EXIT_FAILURE;
}
long offset = atoi(argv[2]);
if (fseek(file, offset, SEEK_SET) == -1) {
puts("Error seeking file...");
return EXIT_FAILURE;
}
fpos_t pos;
if (fgetpos(file, &pos)) {
puts("Error saving seek state...");
return EXIT_FAILURE;
}
size_t size = 0;
for (size_t x = 3; x < argc; x++) {
size += 1 + strlen(argv[x]);
}
unsigned char data[size];
for (size_t x = 4, pos = sprintf(data, "%s", argv[3]); x < argc; x++) {
pos += sprintf(data + pos, " %s", argv[x]);
}
if (finsert(file, pos, data, size)) {
puts("Error modifying file! Possible file corruption...");
return EXIT_FAILURE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment