Reduces your files by two-thirds - C File

C examples for File:File Operation

Description

Reduces your files by two-thirds

Demo Code

#include <stdio.h>
#include <stdlib.h>    // for exit()
#include <string.h>    // for strcpy(), strcat()

#define LEN 40/*from  www .ja  va  2  s .  c om*/

int main(int argc, char *argv[]){
    FILE  *in, *out;   
    int ch;
    char name[LEN];    
    int count = 0;
    
    if (argc < 2){
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if ((in = fopen(argv[1], "r")) == NULL){
        fprintf(stderr, "I couldn't open the file \"%s\"\n",argv[1]);
        exit(EXIT_FAILURE);
    }
    // set up output
    strncpy(name,argv[1], LEN - 5); // copy filename
    name[LEN - 5] = '\0';
    strcat(name,".red");            // append .red
    if ((out = fopen(name, "w")) == NULL){                       
        fprintf(stderr,"Can't create output file.\n");
        exit(3);
    }
    // copy data
    while ((ch = getc(in)) != EOF){
        if (count++ % 3 == 0){
            putc(ch, out);  // print every 3rd char
        }
    }
    if (fclose(in) != 0 || fclose(out) != 0)
        fprintf(stderr,"Error in closing files\n");
    
    return 0;
}

Related Tutorials