Skip to content

Instantly share code, notes, and snippets.

@benmezger
Created July 11, 2017 20:14
Show Gist options
  • Save benmezger/79516ec6b08a59411e05dab2b3d6a263 to your computer and use it in GitHub Desktop.
Save benmezger/79516ec6b08a59411e05dab2b3d6a263 to your computer and use it in GitHub Desktop.
move filename to a fat16 image
int write_dir(FILE *fp, char *fname, struct fat_dir *dir){
strncpy((char *) dir->name, (char *) fname, sizeof(fname));
if (fwrite(dir, 1, sizeof(struct fat_dir), fp) <= 0)
return -1;
return 0;
}
int write_data(FILE *fp, char *fname, struct fat_dir *dir, struct fat_bpb *bpb){
FILE *localf = fopen(fname, "r");
int c;
while ((c = fgetc(localf)) != EOF){
if (fputc(c, fp) != c)
return -1;
}
return 0;
}
void mv(FILE *fp, char *filename, struct fat_bpb *bpb){
if (access(filename, F_OK) < 0)
return;
struct fat_dir *dirs = ls(fp, bpb); // find empty place to store file.
int dirs_len = sizeof (struct fat_dir) * bpb->possible_rentries;
int i;
uint32_t data_addrs = bpb_froot_addr(bpb);
struct fat_dir *curdir;
for (i=0; i < dirs_len; i++){
data_addrs += bpb->bytes_p_sect;
if (dirs[i].name[0] == '\0'){
curdir = &dirs[i]; /* found the first free directory entry */
curdir->starting_cluster = i + 1;
break;
}
else if (dirs[i].name[0] == DIR_FREE_ENTRY){
curdir = &dirs[i];
wipe(fp, curdir, bpb);
return;
}
}
int dir_addr = bpb_froot_addr(bpb) + i * 32;
fseek(fp, dir_addr, SEEK_SET);
off_t filesize = fsize(filename);
if (filesize > 0){
curdir->file_size = filesize;
}
else {
return;
}
if (write_dir(fp, filename, curdir) < 0)
return;
fseek(fp, data_addrs, SEEK_SET);
if (write_data(fp, filename, curdir, bpb) < 0)
return;
bpb->snumber_sect += 1;
free(dirs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment