1.   将绝对路径转换成相对路径。例如, input: /home/news/../tmp/game/../; ouptut: /home/tmp/

  思路:利用栈的思想。每次遇到".."时,将退栈至上一个'/'位置。

 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.\n" );
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.\n" );
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] = '\0';
54 
55     return result;
56 }
57 
58 int main()
59 {
60     char *path = "/home/news/./../tmp/game/../";
61     char *result = NULL;
62 
63     result = convert_path_opt( path );
64     printf( "\nResult is %s.\n", result );
65 
66     return 0;
67 }
View Code

相关文章:

  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-02
  • 2021-12-31
  • 2021-05-11
  • 2021-08-10
  • 2022-12-23
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2022-02-17
  • 2022-12-23
  • 2021-06-02
相关资源
相似解决方案