Search code examples
c++visual-studio-code

VS Code encoding when piping std::out to a file


I copied the below code into ray_tracer.cpp, compiled, and ran ray_tracer.exe > image.ppm. It generated the image I expected when running from the command prompt, but when I ran that code from the VS Code terminal, it generated a file that was twice the size and wasn't the correct format/encoding.

#include <iostream>

int main() {

    // Image

    int image_width = 256;
    int image_height = 256;

    // Render

    std::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n";

    for (int j = 0; j < image_height; j++) {
        for (int i = 0; i < image_width; i++) {
            auto r = double(i) / (image_width-1);
            auto g = double(j) / (image_height-1);
            auto b = 0.0;

            int ir = int(255.999 * r);
            int ig = int(255.999 * g);
            int ib = int(255.999 * b);

            std::cout << ir << ' ' << ig << ' ' << ib << '\n';
        }
    }
}

Here is the format from the command prompt run:

P3
256 256
255
0 0 0
1 0 0
2 0 0
3 0 0

The output from the VS Code run isn't copying nicely, so here's a screenshot:

enter image description here

For what it's worth, both files look identical when opened in VS Code, but if I open the files using File Viewer Plus I see the representations I pasted above.

Is this a known issue? Is there a VS Code setting I can use to duplicate the Command Prompt behavior?


Solution

  • Seems to be an encoding issue. You maybe assume to output UTF-8 - but VS Code is using Powershell and it uses something different than UTF-8. When you materialize it you see strange additional characters.

    You can use WriteConsoleW (Windows API) function to set the output to something that results in a valid output in your final file.

    BTW: Would recommend OpenEXR as an output file -> https://medium.com/@Vertexwahn/image-file-formats-52bbc8a523b4