### IN C /** * This function is responsible for writing image data to a file * T
ID: 3561526 • Letter: #
Question
### IN C
/**
* This function is responsible for writing image data to a file
* The function automatically determines whether the image data is gray scale or rgb
*
* @param char* file_name - The name of the file to be created
* @param int width - The width of the image in pixels
* @param int height - The height of the image in pixels
* @param char* image_data - The image data array to be written to file
* @param int data_length - The length of the image data array
*
* @return int - the numeric value 0 on success, -1 if the image file could not be opened for writing
*/
int write_image(char* file_name, int width, int height, char* image_data, int data_length)
{
int type;
int length = (width)*(height);
int bytes = data_length/length;
int colour;
FILE* fp = fopen(file_name, "wb");
if(fp == NULL)
{
return -1;
printf("unable to open file ");
}
else
{
if(bytes == 1)
{
int type = 5, colour = 7;
}
if(bytes == 3)
{
int type = 6, colour = 127;
}
fprintf(fp, "%d %d %d %d",&type, &width, &height, &colour);
fwrite(image_data, bytes, length, fp);
return 0;
}
fclose(fp);
}
This function is supposed to write a pgm image but it is not passing my submission tests.. any suggestions?
Explanation / Answer
int write_image(char* file_name, int width, int height, char* image_data, int data_length)
{
int type;
int length = (width)*(height);
int bytes = data_length/length;
int colour;
FILE* fp = fopen(file_name, "wb");
if(fp == NULL)
{
return -1;
printf("unable to open file ");
}
else
{
if(bytes == 1)
{
//int type = 5, colour = 7;
type = 5, colour = 7;
/*
* due to this local variable type and colour were
* getting initialized which are not visible outside
* this if block so
* variable type and colour in fprintf later in code
* remains uninitiatized therefore showing garbage value
*/
}
if(bytes == 3)
{
//int type = 6, colour = 127;
type = 6, colour = 127;
}
//fprintf(fp, "%d %d %d %d",&type, &width, &height, &colour);
fprintf(fp, "%d %d %d %d",type, width, height, colour);
/*
* %d expects int but you were passing pointer to variable
* &type is pointer is variable type
* you just need to pass variable type
*/
fwrite(image_data, bytes, length, fp);
return 0;
}
fclose(fp);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.