Home > Backend Development > C++ > How can I embed text files as resources in native Windows applications?

How can I embed text files as resources in native Windows applications?

DDD
Release: 2024-11-17 20:15:02
Original
916 people have browsed it

How can I embed text files as resources in native Windows applications?

Embedding Text Files as Resources in Native Windows Applications

In native Windows programming, it is possible to embed text files into the binary as resources, allowing for convenient access and handling within the application. This is achieved through the creation of user-defined resources.

To embed a text file, create a resource file (.rc) and add entries in the following format:

nameID typeID filename
Copy after login

For example:

IDC_MYTEXTFILE TEXTFILE "mytextfile.txt"
Copy after login

where:

  • IDC_MYTEXTFILE is a unique 16-bit identifier for the resource
  • TEXTFILE is a user-defined resource type (using a number greater than 255)
  • "mytextfile.txt" is the path to the text file

To load and access the embedded text file during runtime:

#include <windows.h>
#include <cstdio>
#include "resource.h"

void LoadFileInResource(int name, int type, DWORD& size, const char*& data)
{
    HMODULE handle = GetModuleHandle(NULL);
    HRSRC rc = FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(type));
    HGLOBAL rcData = LoadResource(handle, rc);
    size = SizeofResource(handle, rc);
    data = static_cast<const char*>(LockResource(rcData));
}

int main()
{
    DWORD size = 0;
    const char* data = NULL;
    LoadFileInResource(IDC_MYTEXTFILE, TEXTFILE, size, data);

    char* buffer = new char[size+1];
    memcpy(buffer, data, size);
    buffer[size] = 0;
    printf("Contents of text file: %s\n", buffer);

    delete[] buffer;
    return 0;
}
Copy after login

Note that the embedded data cannot be modified directly due to its presence within the executable binary. To modify the resource, use the BeginUpdateResource(), UpdateResource(), and EndUpdateResource() functions.

The above is the detailed content of How can I embed text files as resources in native Windows applications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template