user5062925 user5062925 - 3 months ago 28
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".

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.

Answer
#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.