在linux系统下,简单实现类似windows的_splitpath函数的功能

来源:互联网 发布:淘宝刷运费险 编辑:程序博客网 时间:2024/05/22 01:31
在移植一个测试程序的过程中,遇到_splitpath函数,由于没有发现linux系统有类似的函数的,于是自己写了一个代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <libgen.h>


void _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext)
{


 char *tmp_path;
 int conut;
 char tmp[PATH_MAX];
 char tmp_name[PATH_MAX];
 char tmp_ext[PATH_MAX];
 int  check=0;
 int check_1=0;
 int i,j=0,k=0;
 int conut_1,conut_2, conut_3;


 tmp_path = NULL;
 if( ( realpath(path, tmp_path) == NULL) )
 {
  tmp_path = path;
 }


 conut=0;
 do
 {
  if( tmp_path[conut] == ':')
  {
   check=1;
   conut_1 = conut;
  }
  if (tmp_path[conut] == '/')
  {
   conut_2 = conut;
  }
  if (tmp_path[conut] == '.')
  {
   check_1 = 1;
   conut_3 = conut;
  }
  conut++;
 }while(tmp_path[conut] != '\0');


 if ( check == 1)
 {
  fname = basename(tmp_path);
  dir = dirname(tmp_path);
  for( i = 0 ; i< conut; i++)
  {
   if ( dir[i] != ':')
   {
    if( i>=2 )
    {
     tmp[i-2]=dir[i];
    }
   }
   else
   {
    drive=dir[i-1];
    
   }
  }


  memset(dir,0,sizeof(dir));
  strcpy(dir,tmp); 
  
 }
 else
 {
  fname = basename(tmp_path);
  dir = dirname(tmp_path);
  
 }


 if (check_1 == 1)
 {
  while( fname[j] != '\0')
  {


#ifdef 0  //后缀名不带"."
   if ( fname[j] == '.')
   {
    k=j+1;
   }
   else
   {
    tmp_name[j]=fname[j];
    if (j >=k && k != 0)
    {


     tmp_ext[j-k]=fname[j];
    } 
   }


#endif 


#ifdef 1  ////后缀名带"."


if ( fname[j] == '.')
   {
    k=j;
   }


   if ( j >= k && k !=0 )
   {
     tmp_ext[j-k]=fname[j ];
   }
   else
   {
    tmp_name[j]= fname[j];




   }
#endif
   j++;
  }
  memset(ext,0,sizeof(ext));
  memset(fname, 0, sizeof(fname));
  strcpy(fname, tmp_name);
  strcpy(ext,tmp_ext);


 }
 printf("drive=====%c\n",drive);
 printf("dir=======%s\n",dir);
 printf("fname========%s\n",fname);
 printf("ext======%s\n",ext);


}


int main()
{
 char tracePath[PATH_MAX]="c:/test/tmp/share/copytest.test";
 char ext[PATH_MAX];
    char traceFile[PATH_MAX];
 char dir[PATH_MAX];
 char drive[PATH_MAX];


 //strcpy(tracePath,"c:/test/tmp/1234/456/name.c");
 _splitpath(tracePath,drive,dir,traceFile,ext);
 return 0;
}
原创粉丝点击