[Sample] Unmerge two merged files

Discussion in 'iOS Development' started by gojohnnyboi, Feb 22, 2009.

  1. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    this is a follow up to what i showed earlier, the program merging two files. i figured since i had some extra time before basketball i would change that code a bit to reverse what was being done in the merge.

    Code:
    #include <iostream>
    #include <fstream>
    #include <sys/stat.h>
    
    using namespace std;
    
    int fileExists(const char* file) {
    	FILE *checkExists;
    	checkExists = fopen(file, "rw");
    	if(checkExists != NULL) {
    		fclose(checkExists);
    		return 0;
    	}
    	
    	fclose(checkExists);
    	
    	return -1;
    }
    
    int intFromChar(const char* _character) {
    	string swap(_character);
    	int final = atoi(swap.c_str());
    	
    	return final;
    }
    
    int main(int argc, const char *argv[]) {
    	struct stat _mergedFile;
    	struct stat _firstFile;
    	struct stat _secondFile;
    	
    	if(argv[1] != NULL && argv[2] != NULL && argv[3] != NULL && argv[4] != NULL) {
    		if(stat(argv[1], &_mergedFile) == 0) {
    			printf("\nSize of merged file %s: %lld Bytes\n\n", argv[1], (long long)_mergedFile.st_size);
    			if(fileExists(argv[1])==0) {
    				if(fileExists(argv[2]) == 0 || fileExists(argv[3]) == 0) {
    					printf("One or both of the files you wish to split already exist\n");
    					return 0;
    				} else {
    					fstream file_1;
    					ofstream file_2;
    					ofstream file_3;
    					
    					file_1.open(argv[1], ios::in | ios::binary);
    					file_2.open(argv[2], ios::out | ios::binary);
    					file_3.open(argv[3], ios::out | ios::binary);
    					
    					if(!file_1 || !file_2 || !file_3) {
    						printf("Failed to open file(s)\n");
    						return 0;
    					} else {
    						printf("Setup Complete.\n");
    						
    						char _mergedByte;
    						
    						for(int i=0;i<=(long long)_mergedFile.st_size;i++) {
    							file_1.get(_mergedByte);
    							if(i<intFromChar(argv[4])) {
    								file_2.put(_mergedByte);
    							} else {
    								file_3.put(_mergedByte);
    							}
    						}
    						
    						if(stat(argv[2],&_firstFile) == 0 && stat(argv[3],&_secondFile) == 0) {
    							printf("\n\nSize of new file %s: %lld Bytes\n", argv[2], (long long)_firstFile.st_size);
    							printf("Size of new file %s: %lld Bytes\n\n", argv[3], (long long)_secondFile.st_size);
    						}
    					}
    				}
    			} else {
    				printf("Merged file does not exist.\n");
    			}
    		}
    	} else {
    		printf("Usage: %s <merged file> <first file> <second file> <byte split>\n", argv[0]);
    	}
    	
    	return 0;
    }
    it is pretty neat to use in some cases i suppose.

    -John

Share This Page