Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

Assignment 3 -C program to transform a given picture into an up side down picture-System Programming

Using the standard I/O library functions (fopen(), fseek(), fread(), etc), write a C program
to transform a given picture into an up-side-down picture. In particular, your program should
reverse the image by directly reading from one file and writing to another, without the need of
a two-dimensional array.

assign3 system programming

The input image is a grayscale picture, where each pixel has a value between 0(black) and
255(white). The image is simply an nbLines  nbCols matrix of bytes, where each byte store
the gray-level of the corresponding pixel.
nbLines is the number of lines and nbCols is the number of columns.
To help you understand the structure of the binary file containing the image, here is the
function that was used to store the image in a file.
void saveImage(char **image, int nbLines, int nbCols, FILE *fd){
int i;
fputs(“P5\n”, fd); // just a code
fprintf(fd, “%d %d\n”, nbLines, nbCols);
fputs(“255\n”, fd); // another code
for(i=0; i<nbLines; i++)
fwrite(image[i], nbCols, fd);
}

Answer:

void flip(FILE *fp_1, FILE *fp_2, int col, int row, long int size) {
    
    int i;
    char pic[col];
    
    fseek(fp_2, size, SEEK_SET);

    for (i = 0; i < row; ++i) {
        
        fread(pic, 1, col, fp_1);
        fseek(fp_2, -col, SEEK_CUR);
        fwrite(pic, 1, col, fp_2);
        fseek(fp_2, -col, SEEK_CUR);
    }
}

int main(int argc, char *argv[]) {
    
    FILE *fp_1, *fp_2;  
    long int size;
    char temp[100];
    int col, row;
    
    if ((fp_1=fopen(argv[2], "r")) != NULL) { 
    
        if ((fp_2=fopen(argv[3], "w")) != NULL) { 
        
            fseek(fp_1, 0, SEEK_END);
            size = ftell(fp_1);
            rewind(fp_1);
                
            fgets(temp, 100, fp_1);
            fputs(temp, fp_2);

            fscanf(fp_1,"%d %d\n", &col, &row);
            fprintf(fp_2,"%d %d\n", col, row);

            fgets(temp, 100, fp_1);
            fputs(temp, fp_2);
                
            flip(fp_1, fp_2, col, row, size);   
            
        }
            else {
                
                fprintf(stderr, "Error - Cannot open file: %s", argv[2]);   
            }
    }
    
    else {
        
        fprintf(stderr, "Error - Cannot open file: %s", argv[1]);   
    }
    
    fclose(fp_1);   
    fclose(fp_2);   
    
    return 0;
}

About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!