Hi all,

I have a disk file define as

TCHAR szTempFile[MAX_PATH];

What I want to do is, read that file into memory stream. To a buffer. How can I do it.

Dani AI

Generated

Quick summary tied to the thread: is holding a file path in a TCHAR buffer and wants the file contents in memory (and also wants to avoid the write‑to‑disk then read back round‑trip). pointed out path conversion; below are concise, practical options that avoid pitfalls and work on modern compilers.

A simple, portable way (recommended when you can use C++ streams) is to open the file in binary mode, seek to the end to get the size, allocate a buffer and read the whole file once. Example pattern:

std::ifstream in(path, std::ios::binary);
if (!in) throw std::runtime_error("open failed");
in.seekg(0, std::ios::end);
auto size = in.tellg();
std::vector<char> buf(static_cast<size_t>(size));
in.seekg(0);
in.read(buf.data(), buf.size());

Dealing with TCHAR/Unicode paths: if you compile with C++17+ prefer std::filesystem::path (it accepts wide paths on Windows). For older builds use the wide Win32 APIs (CreateFileW/ReadFile) or C runtime _wfopen / wifstream when your path is wchar_t*. Converting wide path to narrow (e.g., wcstombs) works but is brittle—use it only when you understand the code page implications.

If you want to build the contents in memory without touching disk, write to an in‑memory stream: std::ostringstream (or std::wostringstream for wide characters) collects textual output; its .str() gives a std::string/std::wstring that can hold embedded NULs. For very large files or zero‑copy access, use memory‑mapped files (CreateFileMapping/MapViewOfFile) instead.

Quick troubleshooting tips: always open with ios::binary for binary data; check the stream after open/read; beware of enormous files (check size before allocating) and do not treat binary buffers as C strings unless you add a null terminator.

Recommended Answers

All 5 Replies

But on what I confused is that file data type of TCHAR.

Can I used it as ifstream.

No you can't, you'll have to convert it first. If your program ISN'T compiled with unicode: ifstream myfile ((char*)szTempFile); If you ARE using unicode:

#include <cstdlib>
[.......]
const int BUFSIZE = 100;
char buffer[BUFSIZE];
wcstombs(buffer, szTempFile, BUFSIZE );
ifstream myfile (buffer);

Thanks for the replay.

But I do it using ifstream, and seems it works fine.

I got all those things to done because of the following example.

XML Writer in C++

Can you just see it.

What I have done is, output stream write to a disk file and then read the file to memory. It's odd.

So i try to directly write that stream to memory. But wired with it, I can't use char buffer for that.

Can you help me to do it. Any clue..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.