Why are you using temporary space? There's no need for it...

Code:
for(i=Y_min;i<=Y_max;i++){
        fwrite(output[i] + XL, 1, XL - XR + 1, fp);
}
Also, your loops are based on XL..XR and Y_min..Y_max, and yet the values for width and height you output to the file come from somewhere else. This means that if somebody passes a width that is not exactly XL - XR + 1, or a height which is not exactly Y_max - Y_min + 1, things blow up. Why pass the width and height at all, since they can be computed from the rectangle?