Prepending to a string

后端 未结 8 2097
北荒
北荒 2020-12-09 01:49

What is the most efficient way to prepend to a C string, using as little memory as possible?

I am trying to reconstruct the path to a file in a large directory tree.

8条回答
  •  庸人自扰
    2020-12-09 02:36

    This solution has no more copying than necessary. It does require one strlen, so if the directory name retrieval can return the number of bytes copied or if you can precalculate the parent dir string length, you can optimize that away.

    void GetFilename(char *pFile)
    {
        strcpy(pFile, "someFile");
    }
    
    void GetParentDir(char *pDir)
    {
        strcpy(pDir, "/parentdir");
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
        char path[1024];
        GetParentDir(path);
        int dirSize = strlen(path);
        path[dirSize] = '/';
        GetFilename(path + dirSize + 1);
        printf(path);
        return 0;
    }
    

提交回复
热议问题