Prepending to a string

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

    You could maintain the string starting from the end. Since you seem to know the maxSize already...

    So basically if file initially was (foo.txt)

    [] [] [] [] [] [f] [o] [o] [.] [t] [x] [t] [\0]
                 ^
                 |
              lastEmpty           
    

    Now if you add a parent dir a/ it will look like

    [] [] [] [a] [/] [f] [o] [o] [.] [t] [x] [t] [\0]
           ^      
           |      
        lastEmpty           
    

    So the code will look something like (there might be bugs, but you get the idea).

    char temp[LENGTH], file[LENGTH]; 
    int lastEmpty = put_at_end(some_file_name, file);  
    // lastEmpty points to right most empty slot
    
    while (some_condition) { 
        parent_dir = some_calculation_that_yields_name_of_parent_dir; 
    
        int len = strlen(parent_dir);
        char *tmp = parent_dir + len -1;
    
        while (lastEmpty > 0) {
            file[lastEmpty] = *tmp;
            lastEmpty --;
            tmp--;
        }
    } 
    

    Since I suppose we could expect parent_dir to be small, going over it twice should be ok. If you want to pass around the file string, you can just use file+lastEmpty+1.

提交回复
热议问题