/ Published in: C
Convert any file to an "empty" text file (with spaces and tabs).
Expand |
Embed | Plain Text
/* * SpaceTab * * Created by Fabio de Albuquerque Dela Antonio * * fabio914 at gmail.com * */ #include <stdio.h> #include <stdlib.h> #include <string.h> unsigned char * toSpaceTab(unsigned char *, long int); unsigned char * toText(unsigned char *, long int); int main(int argc, char *argv[]) { FILE * in, * out; int option = 0; if(argc < 4) { fprintf(stderr, "Use: %s <input file> <output file> <option>\n", argv[0]); fprintf(stderr, "option: \"-1\" to convert from text to space-tab or \"-2\" to convert from space-tab to text\n"); return 1; } if(!strcmp(argv[3], "-1")) option = 1; else if(!strcmp(argv[3], "-2")) option = 2; else { fprintf(stderr, "Invalid option.\n"); return 1; } if((in = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Could not open input file.\n"); return 1; } fseek(in, 0, SEEK_END); long int fileSize = ftell(in); fseek(in, 0, SEEK_SET); unsigned char * inb, * outb; if((inb = (unsigned char *)malloc(fileSize*sizeof(unsigned char))) == NULL) { fprintf(stderr, "Could not allocate enough memory.\n"); return 1; } if(fread(inb, sizeof(unsigned char), fileSize, in) < fileSize) { fprintf(stderr, "Could not read input file.\n"); return 1; } outb = (option == 1) ? toSpaceTab(inb, fileSize):toText(inb, fileSize); fclose(in); if((out = fopen(argv[2], "w")) == NULL) { fprintf(stderr, "Could not open/create output file.\n"); return 1; } if(fwrite(outb, sizeof(unsigned char), (option == 1) ? fileSize*8:fileSize/8, out) < ((option == 1) ? fileSize*8:fileSize/8)) { fprintf(stderr, "Could not write on output file.\n"); return 1; } fclose(out); free(inb); free(outb); return 0; } unsigned char * toSpaceTab(unsigned char * text, long int fileSize) { unsigned char * outb; unsigned char current; if((outb = (unsigned char *)malloc(fileSize*sizeof(unsigned char)*8)) == NULL) { fprintf(stderr, "Could not allocate enough memory.\n"); exit(1); } register long int i, k = 0; register unsigned char j; for(i = 0; i < fileSize; i++) { current = text[i]; for(j = 0; j < 8; j++) { if((current & (1 << j))) outb[k] = ' '; else outb[k] = '\t'; k++; } } return outb; } unsigned char * toText(unsigned char * spacetab, long int fileSize) { unsigned char * outb; unsigned char current; if((outb = (unsigned char *)malloc(fileSize*sizeof(unsigned char)/8)) == NULL) { fprintf(stderr, "Could not allocate enough memory.\n"); exit(1); } register long int i, k = 0; register unsigned char j; for(i = 0; i < fileSize/8; i++) { current = 0; for(j = 0; j < 8; j++) { if(spacetab[k] == ' ') current |= (1 << j); k++; } outb[i] = current; } return outb; }
You need to login to post a comment.
