-4

I'm having trouble printing the contents of a file to console.

file.bin contents are "abc".

data holds value, but it just doesn't print it...

#include <Windows.h>
#include <iostream>

int main()
{
    wchar_t *data;

    FILE* file;
    int err = _wfopen_s(&file, L"file.bin", L"rb");

    if (err != 0) 
    {
      std::cout << "Error";
      return 0;
    }

    fseek(file, 0, SEEK_END);
    long lSize;
    lSize = ftell(file);
    rewind(file);

    data = (wchar_t *)malloc(lSize + 1);

    fread(data, 1, lSize, file);

    //dereference pointer
    wchar_t data2 = *data;
    std::wcout << data2; // prints nothing...

    system("PAUSE");
    return 0;
}

EDIT

I know about fstream but I would really prefer C style opening/reading files.

  • 1
    Your life would be so much easier with `std::ifstream` (among other things) – Rakete1111 Aug 10 '16 at 19:06
  • 5
    Where to even begin... – Captain Obvlious Aug 10 '16 at 19:06
  • I know theres "include " and a lone "wcout" in there, but this should be retagged as C (IMHO) – Borgleader Aug 10 '16 at 19:08
  • Take a look at this: http://stackoverflow.com/questions/2912520/read-file-contents-into-a-string-in-c – Darth Futuza Aug 10 '16 at 19:08
  • 1
    Does your file.bin really contain UTF-16LE characters? If so, you're almost there, but you need to null-terminate data: `data[lSize/2]=0;` and print the data without dereferencing it: `std::wcout << data;` – rustyx Aug 10 '16 at 19:20
  • _"I would really prefer C style opening/reading files"_ - Dafuq you wanna do that for? – Captain Obvlious Aug 10 '16 at 19:36
  • 1
    What's the encoding of the file? You're only printing the first character, and if it's a BOM encoding that's not a printable character. If it's actually ASCII, you're possibly printing something that your terminal doesn't support, like 慢 (U+6162) or 扡 (U+6261)). (You're also forgetting to check that opening the file and reading it succeeds.) – molbdnilo Aug 10 '16 at 19:44
  • @molbdnilo the file is encoded in Unicode (UTF-16LE) according to notepad, the hex values of file.bin are `FF FE 20 00 61 00 20 00 62 00 20 00 63 00` , (I've also added some error checking) – user5062925 Aug 10 '16 at 19:58
  • 1
    @user5062925 And those first two bytes make an unprintable character (U+FEFF, the BOM) . You need to skip the BOM if it's there. – molbdnilo Aug 10 '16 at 20:05
  • @molbdnilo Alright that helped a lot, thanks! – user5062925 Aug 10 '16 at 20:18

1 Answers1

3
#include <fstream>
#include <string>
#include <iostream>

int main()
{

  std::ifstream ifs("file.bin");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

 std::cout<<content;

  return 0;
}

Use std::ifstream if you're using c++. You're making this much more complicated then you need to. See this former answer.

Community
  • 1
  • 1
Darth Futuza
  • 124
  • 8