【问题标题】:Change the file names.I want to make my code run faster更改文件名。我想让我的代码运行得更快
【发布时间】:2016-07-17 14:32:33
【问题描述】:

定义函数 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;
}

【问题讨论】:

  • return -1?当然你可以想出更合适的方法来返回这里(或者,将函数原型更改为返回int)。另外,请解释到底是什么问题。将您的代码连同标题中的“我想要”一起转储到此处,对于展示您在问题上的努力,或者甚至在解释问题到底是什么(即,是什么让您认为你的代码不够快)!
  • return -1不好,我想实现参数错误然后退出。
  • 您找到了字符串终止符,您可以在其中找到strcpy(buf,"_1");,但您调用strcat,它将重新寻找字符串终止符。
  • 始终检查 (!=NULL) 来自 strtok() 的返回值,以确保操作成功。你怎么知道file指向的缓冲区数组中有足够的空间来容纳新字符。
  • 函数你熟悉吗:basename()

标签: c strtok


【解决方案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()

【讨论】:

    猜你喜欢
    • 2017-08-28
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2017-03-19
    • 2018-08-23
    相关资源
    最近更新 更多