Search code examples
c++file-iounreal-engine4

Reading imported text file to string


I have a project that I am building using Unreal Engine 4, and I am now on to localizing the strings; I have all of the data for each localization in JSON form in text files that I have added to the project's source.

The file structure looks like this in my Solution Explorer:

Games
    MyProject (Target)
        Source
            MyProject
                Localization
                    LOC_ES.txt
                    ...
                Accessor.h
                Accessor.cpp

I added the files to that directory by

  1. Right click on MyProject (the second one) and click add -> new filter
  2. Right click on the Localization filter and click add -> existing item
  3. Select all of the txt files from some other directory on my PC.

I'm not sure, first off, if that's the proper way to add files to a project.


I followed the instructions in this post, but I am getting this error from the engine when I attempt to run this code:

First-chance exception at 0x00007FFBF1B68B9C in UE4Editor.exe: Microsoft C++ exception: std::length_error at memory location 0x000000C38BB2A0C0.

Here is the code as I have entered it. I have tried referencing the text file both with "LOC_ES.txt" and "Localization/LOC_ES.txt" and both give me this error.

std::ifstream t(TCHAR_TO_UTF8(*("Localization/LOC_" + locale + ".txt")));
std::string str;

t.seekg(0, std::ios::end);
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);

str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());

The actual contents of this file are just JSON. Here is an excerpt.

{
    "Single Player":    "Solo Jugador",
    "Multiplayer":      "Multijugador",
    "Options":      "Opciones",
    "Exit":         "Dejar",
    "Back":         "Volver",

    "Normal":       "Normal",
    "Hard":         "Duro",
    "Brutal":       "Extremo"
}

I have never read from a file this way before, so I am not sure what exactly is the problem.


Solution

  • As you wrote in the comments the problem is the file path. My advice for correctly adding the file in Visual Studio is this:

    • First, right-click LOC_ES.txt and chose Remove. Take care that you do not delete the file from the file system.
    • Copy the file in question to a folder inside your project.
    • Add the file as an existing item as you have done before but now chose the file inside the project folder.

    Then you should use a relative file path (depending on where the executable is built).