Skip to content

Instantly share code, notes, and snippets.

@geocar
Created September 9, 2012 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geocar/3685166 to your computer and use it in GitHub Desktop.
Save geocar/3685166 to your computer and use it in GitHub Desktop.
Trim .NDS files to be their minimum size
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
unsigned char d[4];
unsigned char wifi[136];
int fd, i, j, e=0;
unsigned int na, nb, hs;
if (argc <= 1) {
printf("Usage: %s files.nds\n", argv[0]);
}
for (i = 1; i < argc; i++) {
fd = open(argv[i], O_RDWR);
if (fd == -1) {
perror(argv[i]);e++;
continue;
}
/* Read the size word */
if (lseek(fd, 128, SEEK_SET) != 128) goto BAD_NDS;
if (read(fd, d, 4) != 4) goto BAD_NDS;
na = d[0] + (d[1]<<8) + (d[2]<<16) + (d[3]<<24);
/* File size */
nb = lseek(fd, 0, SEEK_END);
if (lseek(fd, na, SEEK_SET) != na) goto BAD_NDS;
/* Quick test to see if there is any work to do */
if (nb == na || ((na-nb) == 136)) {
printf("%s: Already trimmed\n", argv[i]);
close(fd);
continue;
}
/* preserve the WIFI settings (if present) */
if (read(fd, wifi, 136) != 136) goto BAD_NDS;
for (j = 0; j < 136; j++) {
if (wifi[j] == 0 || wifi[j] == 0xff) continue;
na += 136;
break;
}
if (nb < na) {errno=EINVAL;goto BAD_NDS;}
if (nb == na) {
printf("%s: Already trimmed\n", argv[i]);
} else {
/* trim */
(void)lseek(fd,0, SEEK_SET);
if (ftruncate(fd, na) < 0) goto BAD_NDS;
printf("%s: %u bytes saved\n", argv[i], nb-na);
}
(void)close(fd);
continue;
BAD_NDS:
(void)close(fd);
errno = EINVAL;
perror(argv[i]);e++;
}
exit(!!e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment