zoukankan      html  css  js  c++  java
  • linux c实现的提取文件名的小程序

    /*@author etangyushan
     *工作中很多时候会和文件名打交道,有时候只需要文件名称,就写了这么一个小程序
     *这个函数实现了把一个文件的绝对路径和后缀去除,只留下文件名的功能
     * */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //找到最后的slash(/)
    int last_mark (char *str, char mark)
    {
        int site = 0;  
        int count = 0;
        while (site <= strlen(str))
        {
            if (str[site++] == mark)
            {
             count = site; 
            }
        }
        return count;
    }
    
    //找到第一个dot(.)
    int first_mark (char *str, char mark, int num)
    {
        int count = num;
        while (1)  
        {
            if (str[count++] == mark)
            {
                break;
            }
        }
        return count; 
    }
    
    /* 从文件全名中把文件名提取出来,有后缀 */
    int substr_suffix (char *srcstr, char *decstr, int slash)
    {
        int i = 0;
        int size = strlen(srcstr);
        for (i=0; i<size; i++)
        {
            decstr[i] = srcstr[slash++];
        }
    }
    
    /* 从文件全名中把文件名提取出来,去除后缀 */
    int substr (char *srcstr, char *decstr, int lastslash, int firstdot)
    {
        int i = 0;
        //printf("last=%d,first=%d
    ", lastslash, firstdot);
        //printf("size=%d
    ", firstdot-lastslash);
        int size = firstdot-lastslash-1;
        for (i=0; i<size; i++)
        {
            //printf("...%c...
    ",srcstr[lastslash]);
            decstr[i] = srcstr[lastslash++];
        }
    }
    
    //测试
    int main()
    {
        char *file = "/root/etc/init.d/myte123456789abcedefadfaefsa1234.c";
        char filename[256] = {};
        char filename_nosuffix[256] = {};
    
        int lastnum = last_mark (file, '/');
        int firstnum = first_mark (file, '.', lastnum);
    
        substr_suffix (file, filename, lastnum);
        printf ("filename = %s
    ", filename);
    
        substr (file, filename_nosuffix, lastnum, firstnum);
        printf ("filename no suffix = %s
    ", filename_nosuffix);
    }
  • 相关阅读:
    在Codeblocks下配置GoogleTest单元测试工具
    自制贪吃蛇游戏中的几个“大坑”
    贪吃蛇“大作战”(进阶篇)
    贪吃蛇“大作战”(终结篇)
    贪吃蛇“大作战”(六)
    贪吃蛇“大作战”(五)
    贪吃蛇“大作战”(四)
    贪吃蛇“大作战”(三)
    小心!选择的陷阱
    贪吃蛇“大作战”(二)
  • 原文地址:https://www.cnblogs.com/etangyushan/p/3709954.html
Copyright © 2011-2022 走看看