更改文件名。我想让我的代码运行得更快

时间:2016-07-17 14:32:33

标签: c strtok

定义函数char * filename(char * file,int num) 要求:输入文件名:test.txt 1 输出:test_1.txt 输入:测试 输出:test_1

这是我的代码

char *filename(char *file, int num)
{
    if(NULL == file || num <= 0)        
    {
        printf("parameter error\n");
        return -1;
    }

    char *buf = file, *ptr1, *ptr2, *ptr3;
    char temp[num];

    while (*buf != '.' && *buf != '\0') 
    {
        buf++;
        if(*buf == '\0')
        {
            strcat(file ,"_1");
            return 0;
        }
    }

    ptr1 = strtok(file, ". ");  
    ptr2 = strtok(NULL, ". ");  
    ptr3 = strtok(NULL, ". ");  

    strcpy(temp, ptr2); 

    strcat(file, "_");  
    strcat(file, ptr3); 
    strcat(file, ".");  
    strcat(file, temp); 

    return 0;
}

1 个答案:

答案 0 :(得分:1)

以下代码干净地编译并执行所需的功能

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_DIGIT_LEN (15)

char *filename(char *file, int num)
{
    char * modifiedFileName = NULL;
    if( NULL == (modifiedFileName = malloc( strlen( file) +MAX_DIGIT_LEN ) ) )
    {
        perror( "malloc for room for expanded file name failed");
        //exit( EXIT_FAILURE );
        return NULL;
    }

    // implied else, malloc successful

    char * base = NULL;
    if( NULL == (base =  strtok( file, ".") ) )
    {
        perror( "strtok failed to find . in file name");
        //exit( EXIT_FAILURE );
        return NULL;
    }

    // implied else, strtok found .

    strcpy( modifiedFileName, base );
    char newChars[ MAX_DIGIT_LEN ] = {'\0'};  // 15 to allow for large numbers
    sprintf( newChars, "_%d.", num);

    strcat( modifiedFileName, newChars );

    char * ext = NULL;
    ext = base + strlen(base);

    strcat( modifiedFileName, ext );

    return( modifiedFileName );
} // end function: filename

当然,调用者在使用它时需要将返回的指针传递给free()