1. 将绝对路径转换成相对路径。例如, input: /home/news/../tmp/game/../; ouptut: /home/tmp/
思路:利用栈的思想。每次遇到".."时,将退栈至上一个'/'位置。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 char *convert_path_opt( const char *path ) 6 { 7 char *result = NULL; 8 int top = 0; 9 int path_len = 0, 10 index = 0, 11 point_cnt = 0; 12 13 /**< check */ 14 if ( NULL == path ) 15 { 16 fprintf( stderr, "convert_path_opt: invalid argument. " ); 17 return NULL; 18 } 19 20 /**< allocate memory */ 21 path_len = strlen( path ); 22 result = (char *)malloc( path_len * sizeof(char) ); 23 if ( NULL == result ) 24 { 25 fprintf( stderr, "convert_path_opt: failed to malloc. " ); 26 return NULL; 27 } 28 29 /**< convert */ 30 while ( index < path_len ) 31 { 32 /**< copy characters before point. */ 33 while ( index < path_len && path[index] != '.' ) 34 { 35 result[top++] = path[index++]; 36 } 37 38 /**< counter point. */ 39 for ( point_cnt = 0; 40 index < path_len && path[index] == '.'; 41 ++point_cnt, ++index ); 42 43 if ( point_cnt == 2 ) 44 { 45 --top; 46 while ( --top > 0 && result[top] != '/' ); 47 ++top; 48 } 49 50 ++index; 51 } 52 53 result[top] = '