int putFile(SuperBlock *super_block, FILE *fp, char *file_name, char *new_file_name){ FILE *new_fp = fopen(file_name, "rb"); if(new_fp == NULL){ fprintf(stderr,"File not found.\n"); return -1; } int file_size_bytes, block_size, bytes_read, file_size_blocks; file_size_bytes = block_size = bytes_read = file_size_blocks = 0; block_size = ntohs((*super_block).block_size); char block[block_size]; char *FAT_blocks = NULL; readFATBlocks(&FAT_blocks, super_block, fp); while((bytes_read = fread(block, 1, sizeof(block), new_fp)) > 0 ){ //read in data of (at most) one block size file_size_bytes += bytes_read; //found file size (in blocks) file_size_blocks++; } int free_blocks[file_size_blocks]; if(getFreeBlocks(FAT_blocks, free_blocks, super_block, file_size_blocks) < 0){ printf("No free space on disk.\n"); exit(EXIT_FAILURE); } int block_index, size, first_block; //get file size first_block = -1; size = block_size; //allocate one block fseek(new_fp, 0, SEEK_SET); for(block_index = 0; block_index < file_size_blocks; block_index++){ memset(block, 0, sizeof(block)); if(block_index == (file_size_blocks - 2)){ //last case where you may want to read in less than 512 bytes size = file_size_bytes - ((file_size_blocks - 1) * block_size); } fread(block, sizeof(block), 1, new_fp); fseek(fp, free_blocks[block_index] * 512, SEEK_SET); //move to correct mem location fwrite(block, size, 1, fp); //write one block if(first_block < 0) { first_block = free_blocks[block_index]; } } //write the fat blocks to FAT table writeFATBlocks(first_block, free_blocks, super_block, fp, file_size_blocks); writeFileEntry(super_block, fp, first_block, file_name, new_file_name, file_size_blocks, file_size_bytes); fprintf(stderr,"File succsessfully put in disk image.\n"); fclose(new_fp); return 0; }
int main ( int argc, char *argv[] ) { char *diskFileName = argv[1]; char *hostFileName = argv[2]; FILE* diskFile; diskFile = fopen(diskFileName,"r"); FILE* hostFile; hostFile = fopen(hostFileName,"r"); if(diskFile == NULL) { printf("File not found.\n"); return 0; } if(hostFile == NULL) { printf("File not found.\n"); return 0; } fclose(hostFile); int blockSize = readBlockSize(diskFile); int fatStart = readFATStart(diskFile); int numFatBlocks = readFATBlocks(diskFile); int rootDirStart = readDirStart(diskFile); int numRootDirBlocks = readDirBlocks(diskFile); int* fatInfo; fatInfo = findFATBlocks(diskFile, fatStart, numFatBlocks, blockSize); int availableBlocks = fatInfo[0]; fclose(diskFile); putFileOnClient(diskFileName, hostFileName, availableBlocks, rootDirStart, numRootDirBlocks, blockSize, fatStart, numFatBlocks); return 1; }