Improving C style string usage

I've been playing Valve games for quite some time, but I've never been good at using char arrays for string management. I REALLY would like to improve, given how much time I spend on them. Obviously, using the correct lines would be nice, but since all SDK functions return char * or accept it as args, it does not do much to convert the fourth as well. Does anyone have any good links, how much do they better understand them? Most of what I find on Google just were snippets.

Also, I am trying to parse a very simple text file. The main content is as follows:

PatchVersion = 1.1.1.2 ProductName = l4d APPID = 440

I want to get PatchVersion and ProductName. My code looks something like this, but really just the lack of proper knowledge left me in a dead end. strtok only retrieves the token before the '=' sign, strchr gives me a pointer to its location, but just doesn't know a good method.

bool ParseSteamFile()
{
    FileHandle_t file;
    file = filesystem->Open("steam.inf", "r", "MOD");

    if(file)
    {
        int size = filesystem->Size(file);
        char *line = new char[size + 1];

        while(!filesystem->EndOfFile(file))
        {
            char *subLine = filesystem->ReadLine(line, size, file);
            Msg("SUBLINE: %s\n", subLine);

            char *buffer = "";

            if(strstr(subLine, "PatchVersion"))
            {
                char *c = strtok(subLine, "=");
                while(c != NULL)
                {
                    Msg("Token: %s\n", c);
                    c = strtok(subLine, "=");
                }
            }
        }
    }
}
+3
source share
4 answers

There is nothing wrong with using C-strings. However, you will need to write pretty, very very low-level code that has already been abstracted when using String objects.

C-String ( , ascii ) . , , , cplusplus.com .

strtok , subLine:

      char *c = strtok(subLine, "=");
        while(c != NULL)
        {
            Msg("Token: %s\n", c);
            c = strtok(null, "=");
        }

, :

PatchVersion
=1.1.1.2 ProductName
=l4d appID
=440

, strtok , subLine .

, -. - . scanf . name value:

char * name = new char[255];
char * value = new char[255];
sscanf(subLine, "%s=%s", name, value);

strncpy . sscanf , subLine ( tr% s =% s , ).

, , . , , , , ( ) .

+2
sscanf(*subLine, "PatchVersion=%s ProductName=%s appID=%d", patchVersion, productName, &appID);

, , , .

+2

, , SDK char * args, , .

= const char *, SDK , - .c_str() SDK. , , , std::string , , , , , . std::string . C-, asprintf() ( , sprintf() / snprintf(), malloc(), realloc() ..) , . stringstreams ... .str(), .c_str(), const char *.

( ), sscanf(), . , strchr '='.

0

, Boost String Algorithms, , std::string exposes char , C.

0

Source: https://habr.com/ru/post/1773159/


All Articles