user5062925 user5062925 - 1 year ago 82
C++ Question

C++ reading a file prints nothing to console

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

file.bin contents are "abc".

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);

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

fread(data, 1, lSize, file);

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

return 0;


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

Answer Source
#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>()    ) );


  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.