-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileCompressor.c
More file actions
500 lines (397 loc) · 12.8 KB
/
Copy pathfileCompressor.c
File metadata and controls
500 lines (397 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include "FrequencyTree.h"
#include "Tree.h"
#include "MinHeap.h"
#include "Dictionary.h"
#define MAX_FILES 1000000
/**
* This function takes a starting directory path and a array to which file paths need
* to be appended.
* numFiles are files appended to array currently.
* If recursive variable is not 0, then this function scans all the directories recursively.
* Else, only the current directory is scanned.
*/
void getFilePathsFromDir(char *startPath, char **filePaths, int *numFiles, int recursive) {
struct stat path_stat;
stat(startPath, &path_stat);
// if given path represents a file, just add the path to list and return
if(S_ISREG(path_stat.st_mode)) {
filePaths[*numFiles] = strdup(startPath);
//printf("%s\n", startPath);
*numFiles += 1;
return;
}
struct dirent * dir;
DIR * d = opendir(startPath); // open the directory
if(d == NULL) {
printf("Check Input. Invalid path. Unable to open: %s\n", startPath);
exit(1);
}
// read entries from directory.
while ((dir = readdir(d)) != NULL) {
char *pathStr = malloc(sizeof(char) * (10 + strlen(startPath) + strlen(dir->d_name)));
pathStr[0] = '\0';
sprintf(pathStr, "%s/%s", startPath, dir->d_name);
// if the entry is not a directory
if(dir-> d_type != DT_DIR) {
filePaths[*numFiles] = strdup(pathStr);
//printf("%s\n", pathStr);
*numFiles += 1;
// or if directory is a valid child directory
} else if(recursive && dir -> d_type == DT_DIR &&
strcmp(dir->d_name,".")!=0 &&
strcmp(dir->d_name,"..")!=0 ) {
getFilePathsFromDir(pathStr, filePaths, numFiles, recursive);
}
free(pathStr);
}
closedir(d); // finally close the directory
}
/***********************************************************
* this function reads the file and creates token by splitting
* the content by whitespace chars. It then insert all the tokens
* including whitespaces into a FreqTree, which maintains count of
* inserted words.
***********************************************************/
void fillWordCountTree(FreqTree *tree, char *fileName) {
int filedesc = open(fileName, O_RDONLY);
if(filedesc < 0){
printf("Error in reading file: %s\n", fileName);
return;
}
char word[500];
int len = 0;
char c;
// read one by one character
while(read(filedesc, &c, 1) == 1) {
if(isspace(c)) {
// we need to break our word
if(len != 0) {
word[len] = '\0';
insertFreqTree(tree, word);
}
len = 0;
// now insert your whitespace also to the tree.
word[0] = c;
word[1] = '\0';
insertFreqTree(tree, word);
} else {
// add current character to the current word
word[len++] = c;
}
}
// insert last word
if(len != 0) {
word[len] = '\0';
insertFreqTree(tree, word);
}
close(filedesc);
}
/*************************************************
* Utility function to check if file name ends with a
* .hcz extension
************************************************/
int endsWithHcz( char *filePath ) {
filePath = strrchr(filePath, '.');
if( filePath != NULL )
return (strcmp(filePath, ".hcz") == 0);
return 0;
}
/**********************************************************
* this method takes a input file and a codebook and using
* the codebook, compresses the input file and creates a
* <input>.hcz compressed file.
*********************************************************/
// compression code for single file
void compressSingleFile(char *fileName, Dict *wordToCode) {
int readerDesc = open(fileName, O_RDONLY);
if(readerDesc < 0){
printf("Error in reading file: %s\n", fileName);
//fflush(stdout);
return;
}
// open file for writing the compressed version
char *path = malloc(sizeof(char) * (strlen(fileName) + 10));
path[0] = '\0';
strcat(path, fileName);
strcat(path, ".hcz");
int writerDesc = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if(writerDesc < 0){
printf("Error in writing file: %s\n", path);
//fflush(stdout);
free(path);
return;
}
char word[500];
int len = 0;
char c;
char *code;
// read character by character
while (read(readerDesc, &c, 1) == 1) {
if(isspace(c)) {
// we need to break our word
if(len != 0) {
word[len] = '\0';
code = findValue(wordToCode, word);
if(code != NULL) {
write(writerDesc, code, strlen(code));
}
}
len = 0;
// now insert your whitespace also to the tree.
word[0] = c;
word[1] = '\0';
// check if currently read word exists in dictionary
code = findValue(wordToCode, word);
if(code != NULL) {
write(writerDesc, code, strlen(code));
}
} else {
// add current character to the current word
word[len++] = c;
}
}
// insert last word
if(len != 0) {
word[len] = '\0';
code = findValue(wordToCode, word);
if(code != NULL) {
write(writerDesc, code, strlen(code));
}
}
free(path);
close(writerDesc);
close(readerDesc);
}
// this method compresses all the given files in list using the same
// codebook.
void compressAllFiles(char **filePaths, int numFiles, char *codeBook) {
// Create Codebook with word -> Code mapping
Dict *wordToCode = readHuffmanCodebook(codeBook);
int count = 0;
int processedFiles = 0;
while(count < numFiles) {
if(!endsWithHcz(filePaths[count])) {
printf("Compressing: %s\n", filePaths[count]);
compressSingleFile(filePaths[count], wordToCode);
processedFiles++;
}
// move to next file
count++;
}
freeDict(wordToCode);
printf("Compressed %d files successfully using %s codebook.\n", processedFiles, codeBook);
//fflush(stdout);
}
/**********************************************************
* this method takes a input compressed file as <file>.hcz
* and a code to word Dictionary. The decompressed file is
* written with name <file>
* The compressed file should only contain 1 and 0.
*********************************************************/
// decompression logic for a single file.
void decompressSingleFile(char *fileName, Dict *CodeToWord) {
int readerDesc = open(fileName, O_RDONLY);
if(readerDesc < 0){
printf("Error in reading file: %s\n", fileName);
return;
}
// create a path for output file with .hcz removed from fileName.
char *outPath = malloc(sizeof(char) * (10 + strlen(fileName)));
strncpy(outPath, fileName, strlen(fileName) - 4);
outPath[strlen(fileName) - 4] = '\0';
int writerDesc = open(outPath, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if(writerDesc < 0){
printf("Error in writing file: %s\n", outPath);
free(outPath);
return;
}
// Now read the input file character by character
char word[500];
int len = 0;
char c;
while (read(readerDesc, &c, 1) == 1) {
word[len++] = c;
word[len] = '\0';
// check if currently read code exists in dictionary
char *token = findValue(CodeToWord, word);
if(token != NULL) {
// It was a valid word, and hence, we can print to file
write(writerDesc, token, strlen(token));
// reset current code,
len = 0;
}
}
// close files.
free(outPath);
close(writerDesc);
close(readerDesc);
}
// this method decompresses all the given files in list using the same
// codebook.
void decompressAllFiles(char **filePaths, int numFiles, char *codeBook) {
// Original Codebook has word -> Code mapping
Dict *wordToCode = readHuffmanCodebook(codeBook);
// We need dictionary with Code -> word mapping, so
// get reversed dictionary
Dict *CodeToWord = getReverseDict(wordToCode);
int count = 0;
int processedFiles = 0;
while(count < numFiles) {
if(endsWithHcz(filePaths[count])) {
printf("Decompressing: %s\n", filePaths[count]);
decompressSingleFile(filePaths[count], CodeToWord);
processedFiles++;
}
// move to next file
count++;
}
// free the dictionaries
freeDict(wordToCode);
freeDict(CodeToWord);
printf("Decompressed %d files successfully using %s codebook.\n", processedFiles, codeBook);
}
/**************************************************************************
* This method takes a list of files, and after reading them creates a huffman
* codebook on the basis of words inside all the given files.
*************************************************************************/
void createCodeBook(char **filePaths, int numFiles, char *outputCodeBook) {
// Change code here to fill a created FreqTree..
// The method should read the file, and fill FreqTree only.
// That way, we can use it for multiple files.
FreqTree *wordCountTree = createFreqTree();
int count = 0;
int processedFiles = 0;
while(count < numFiles) {
if(!endsWithHcz(filePaths[count])) {
printf("Processing: %s\n", filePaths[count]);
fillWordCountTree(wordCountTree, filePaths[count]);
processedFiles++;
}
count++;
}
//printf("Could created the Frequency tree from all files successfully\n");
MinHeap *minHeap = convertFreqTreeToMinHeap(wordCountTree);
freeFreqTree(wordCountTree); // free FreqTree, its work is done.
//printf("Could created the Min Heap successfully\n");
TreeNode *huffmanTree = convertMinHeapToHuffManTree(minHeap);
freeMinHeap(minHeap); // free MinHeap, its work is done.
//printf("Could created the Huffman Tree successfully\n");
Dict *codeDictionary = dictionaryFromHuffman(huffmanTree);
freeTree(huffmanTree); // free huffmanTree, its work is done.
//printf("Could created the Code Dictionary successfully\n");
saveDictionary(codeDictionary, outputCodeBook);
freeDict(codeDictionary); // free dictionary, its work is done.
printf("Processed %d files.\n", processedFiles);
printf("Saved Codebook %s successfully\n", outputCodeBook);
}
/**************************************************************************
* This method shows the correct way of using the utility.
*************************************************************************/
void showUsage() {
printf("./fileCompressor [-R] <flag> <path or file> |codebook|\n");
printf("Valid Flags: b, c, d\n");
printf("-R: recursive\n");
printf("Codebook is required if flag is c or d\n");
}
/**************************************************************************
* Main method:
* It checks for required paramters, derives the list of files to be used
* and then invoke appropriate module(compress, decompress, buildCodebook)
*************************************************************************/
int main(int argc, char *argv[]) {
int option;
// flags to check what user wants to do
int buildFlag = 0;
int compressFlag = 0;
int decompressFlag = 0;
// are all files inside folder need to be considered.
int recursive = 0;
// input directory/file path
char *dirPath = NULL;
// Codebook to be used for compress/decompress
char *codebook = NULL;
// set this module, to not display getopt module errors.
// we are showing our own errors.
opterr = 0;
// Below we are allowing b, c, d as options to contains value
// and R to be without value.
while ((option = getopt(argc, argv, "bcdR")) != -1) {
switch (option)
{
case 'b':
buildFlag = 1;
break;
case 'c':
compressFlag = 1;
break;
case 'd':
decompressFlag = 1;
break;
case 'R':
recursive = 1;
break;
case '?':
if (isprint(optopt))
printf ("Unknown option `-%c'.\n", optopt);
else
printf ("Unknown option character `\\x%x'.\n", optopt);
exit(1);
default:
exit(1);
}
}
while (optind < argc) {
// Extra parms go in dirPath and codeBook
if(dirPath == NULL) {
dirPath = argv[optind];
} else if(codebook == NULL) {
codebook = argv[optind];
}
// else ignore extra params
optind++; // go to the next argument
}
int setFlags = 0;
if (buildFlag) setFlags++;
if (compressFlag) setFlags++;
if (decompressFlag) setFlags++;
if(setFlags != 1) {
printf("Exactly one flag out of b, c & d can be set.\n");
showUsage();
return 1;
}
if((compressFlag || decompressFlag) && (codebook == NULL)) {
printf("Flags c & d must provide codebook.\n");
showUsage();
return 1;
}
printf("Starting to Read all the files or the file paths in dictionaries\n");
//fflush(stdout);
// create the list of all the files (recursive if required)
char **filePaths = malloc(sizeof(char *) * MAX_FILES);
int numFiles = 0;
getFilePathsFromDir(dirPath, filePaths, &numFiles, recursive);
// Based on user operation, call required method.
if(buildFlag) {
createCodeBook(filePaths, numFiles, "HuffmanCodebook");
} else if(compressFlag) {
compressAllFiles(filePaths, numFiles, codebook);
} else if(decompressFlag) {
decompressAllFiles(filePaths, numFiles, codebook);
}
// free memory from file array
int i;
for(i=0; i<numFiles; i++) {
free(filePaths[i]);
}
free(filePaths);
return 0;
}