Prepending to a string

后端 未结 8 2100
北荒
北荒 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:25

    You can climb to the top of the directory tree keeping the names as you go along, then paste the names together all at once. At least then you aren't doing unnecessary copies by pushing onto the front.

    int i = 0;
    int j;
    
    char temp*[MAX_DIR_DEPTH], file[LENGTH];
    
    while (some_condition) {
        temp[i++] = some_calculation_that_yields_name_of_parent_dir;        
    }
    
    char *pCurrent = file;    
    for( j = i-1; j > 0; j-- )
    {
        strcpy(pCurrent, temp[j]);
        pCurrent += strlen(temp[j]);
        *pCurrent++ = '\';
    }
    strcpy(pCurrent, filename);
    *pCurrent = 0;
    

提交回复
热议问题