Advertisement
NovaYoshi

Bad file header cleaner thing

Aug 1st, 2017
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 KB | None | 0 0
  1. #include <dirent.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8.  
  9. void check_file(const char *path) {
  10.   FILE *file = fopen(path, "rb");
  11.   if(!file)
  12.     return;
  13.   fseek(file, 0, SEEK_END);
  14.   int size = ftell(file);
  15.   rewind(file);
  16.  
  17.   unsigned char *buffer = (char*)malloc (sizeof(char)*size);
  18.   if(!buffer)
  19.     goto error;
  20.   int result = fread(buffer, 1, size, file);
  21.   if(result != size)
  22.     goto error;
  23.  
  24.   int bad = buffer[14] || buffer[15];
  25.  
  26.   if(bad) {
  27.     printf("Fixing bad header: %s\n", path);
  28.     for(int i=0; i<15; i++)
  29.       printf("%.2X ", buffer[i]);
  30.     putchar('\n');
  31.  
  32.     fclose(file);
  33.     file = fopen(path, "wb");
  34.     if(!file) {
  35.       puts("Couldn't open the file for writing to fix it though");
  36.       goto error;
  37.     }
  38.     for(int i=7; i<16; i++) // clear out the last 9 bytes of the header
  39.       buffer[i] = 0;
  40.     fwrite(buffer, sizeof(char), size, file);
  41.   }
  42.  
  43. error:
  44.   free(buffer);
  45.   if(file)
  46.     fclose(file);
  47. }
  48.  
  49. int is_directory(const char *path) {
  50.   struct stat statbuf;
  51.   if (stat(path, &statbuf) != 0)
  52.       return 0;
  53.   return S_ISDIR(statbuf.st_mode);
  54. }
  55.  
  56. void scan(const char *name) {
  57.   DIR *d;
  58.   struct dirent *dir;
  59.   d = opendir(name);
  60.   if(d) {
  61.     while ((dir = readdir(d)) != NULL) {
  62.        if(dir->d_name[0] == '.')
  63.          continue;
  64.        char full_path[500];
  65.        sprintf(full_path, "%s/%s", name, dir->d_name);
  66.        if(is_directory(full_path)) {
  67.          scan(full_path);
  68.          continue;
  69.        }
  70.        char *extension = strrchr(dir->d_name, '.');
  71.        if(!extension)
  72.          continue;
  73.        if(strcasecmp(extension+1, "nes"))
  74.          continue;
  75.  
  76.        check_file(full_path);
  77.     }
  78.     closedir(d);
  79.   }
  80. }
  81.  
  82. int main(int argc, char *argv[]) {
  83.   scan(".");
  84.   return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement