Writing PPM Files
The writer is a small, fixed sequence: open the file in binary mode, write the ASCII header, write the raw pixel bytes.
function write_ppm(filename, image, width, height):
file = fopen(filename, "wb") # binary mode matters, even on
# platforms where it is a no-op
fprintf(file, "P6\n%d %d\n255\n", width, height)
fwrite(image, 1, width * height * 3, file)
fclose(file)
The one detail worth being deliberate about in the actual C implementation is opening with "wb", not "w". On Linux this makes no difference, but writing the habit into your code now means it also works correctly if you ever build or test on Windows, where text mode silently rewrites 0x0A bytes and will corrupt raw pixel data that happens to contain that byte value.