1

I am trying to write a string directly to the console buffer in C++ using WriteConsoleOutputCharacter. I read the contents of a file which contains multiple \n characters but when I write to the console buffer it doesn't write the rest of the file on the next line instead it writes ??. In notepad it says my file encoding is utf-8. I wondered if this had anything to do with it but when I print the file contents using cout the line breaks where ever it encounters \n.

std::ifstream file("debug.txt");
   static HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
   DWORD ir = 0;
   if (file.is_open()) {
       file.seekg(0, file.end);
       int len = file.tellg();
       std::cout << len;
       file.seekg(0, file.beg);
       char* string = (char*)calloc(len+1, sizeof(char));
       string[len] = '\0';
       file.read(string, len);
       file.close();
       COORD coord = { 0, 0 };
       WriteConsoleOutputCharacterA(
           console,
           string,
           len,
           coord,
           &ir
       );

       free(string);

This is how I read from the file and write to the console buffer. Any thoughts?

Christophe
  • 54,708
  • 5
  • 52
  • 107
  • I didn't really see the need for std::vector. I don't need it in this instance. I also tried your suggestion, it didn't work. –  Apr 06 '20 at 00:33
  • About `WriteConsoleOutputCharacterA()`, I've no experience but: `int len = file.tellg();` gives you the length of file in bytes. If you `file.read(string, len);` on Windows the file reading turns Windows line-endings (`\r\n`) into C line-endings (`\n`). Hence, you may receive less bytes than `len` in `string`. (Guess about the rest.) I'm not sure whether `std::ios::gcount()` returns the number of bytes read from file or the number of bytes stored. However, if you open the file as binary (i.e. `std::ifstream file("debug.txt", std::ios::binary);`) then no conversion will happen. – Scheff's Cat Apr 06 '20 at 04:20
  • I realized that was the issue. It also caused me some others issues so I just kept scanning the file character by character until I reach end of file instead. I used while (!file.eof()) stream << file.get(); –  Apr 07 '20 at 05:03
  • Better would have been `for (char c; file >> c;) { /* process c */ }` or `for (char c; file.get(c);) { /* process c */ }`. ;-) [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/a/5605159/7478597) – Scheff's Cat Apr 07 '20 at 05:08

0 Answers0