2009-07-16 4 views
0
I have written this simple C program that changes the rotation file name. 
Eg: 
For A_B_C_1 
Need to rotate it to 
A_B_C_2 
and 
if A_B_C 
need to rotate it to A_B_C_1 

Problem is the strncat is not working as expectedly. It is giving me output like: 

A_B_C_1 (Works fine for single instance) 
A_B_C_2 
A_B_C_23 
A_B_C_2324 

Logic used is simple:get the last digit in the string if it exists. 
If it does not simply append _1 (This one is working fine) 
If it does - extract the number, increment it and append to the new string. 

Is there some std library that does this? 

Gives error on calling this method in a loop/multiple times.... 

원인을 디버그 할 수 없습니다. 도움이 필요하면 안내하십시오. 로그 파일 순환 이름

 
     int getRotationFileName(char *sFileName,char *sNewFileName) 
     { 
     char sTmpFile[256]; 
     int newRotation; 
     memset(sTmpFile,NULL,sizeof(sTmpFile)); 
     strncpy(sTmpFile, sFileName, strlen(sFileName)); 
     char *tokenPtr; 
     strtok(sFileName,"_"); //a 
     strtok(NULL, "_"); //b 
     strtok(NULL, "_"); //c 
     tokenPtr = strtok(NULL, "_"); //1 
      printf("sTempFile [%s], sFileName [%s], token [%s]", 
       sTmpFile,sFileName,tokenPtr); 


     if(tokenPtr!= NULL)//Last - exists 
     { 

      newRotation = atoi(tokenPtr); 
      int newLen = strlen(sTmpFile); 
      int oneLen = strlen(tokenPtr); 
      memset(sNewFileName, NULL, sizeof(sNewFileName)); 
      printf("sNewFileName is prior: %s and len is %d \n", 
      sNewFileName, (newLen-oneLen)); 
      printf("sTempName is prior: %s", sTmpFile); 
     strncpy(sNewFileName,sTmpFile, (newLen-oneLen)); 

      printf("diff is %d\n", (newLen-oneLen)); 
      printf("sNewFileName before concat %s \n", sNewFileName); 
      newRotation++; 
      sprintf(sNewFileName,"%s%d",sNewFileName, newRotation); 
      sNewFileName[strlen(sNewFileName)]='\0'; 
      printf("sNewFileName after concat %s \n", sNewFileName); 
     } 
     else 
     { 
      printf("in else TmpFile [%s] , New File [%s], len %d",sTmpFile, 
     sNewFileName,strlen(sTmpFile)); 
      strcat(sTmpFile,"_1"); 
      strncpy(sNewFileName,sTmpFile, strlen(sTmpFile)); 
     } 
     strcpy(sFileName, sNewFileName); 
     printf("\nNew file created is %s\n",sNewFileName); 
     return 1; 
} 
는 라인에 문제가있는 것 같다 :를 strncpy (sNewFileName, sTmpFile (newLen-oneLen));

피드백 : 코드 포매터는 크롬 브라우저

+0

소스 코드의 형식이 꽤 엉망입니다 ... 코드를 게시하려면 4 개의 공백을 들여 쓰기 만하면됩니다. –

+0

나는 그것을 고쳤지만 수정 사항이 되돌려졌다. Chrome의 "feedback"라인이 의미하는 바라고 생각한다. 기묘한. 수정 된 버전이 수정 내역에 있으므로 다시 적용하십시오. :) – unwind

+0

작은 업데이트 : 초기 이름에 숫자가있을 수 있으며 필요한 경우 증분 된 숫자로 마지막 밑줄을 추가하기 전에 두 개의 밑줄을 확인해야합니다. – techzen

답변

1

귀하의 코드는 ... 약간 혼란이 사이트에 제대로 작동하지 않습니다. 알고리즘을 단계별로 분할해야하는데, 각 단계는 쉽게 수행 할 수 있어야합니다.

  • 이름이 숫자로 끝나는 지 확인하십시오. 그렇다면 번호가 시작된 위치를 기록하고 번호를 추출하십시오. 그렇지 않은 경우 0으로 끝나는 것처럼 행동하십시오.
  • 숫자를 증가시킵니다.
  • 접두사와 숫자 (문자열)를 연결하여 새 문자열을 만듭니다.

일반적으로 표준 라이브러리가 고유 한 이름을 생성하도록하는 것이 더 좋은 방법입니다.

void rotateName(const char *oname, char *nname) 
{ 
    const char *ptr; 
    int   number, plen; 

    for(ptr = oname; *ptr && !isdigit(*ptr); ptr++) 
      ; 
    if(*ptr == '\0') 
      number = 0; 
    else 
      number = atoi(ptr); 
    plen = ptr - oname; 
    if(plen <= 0) 
      return; 
    memcpy(nname, oname, plen); 
    sprintf(nname + plen, "%d", number + 1); 
} 
0

사용 예 :

여기서 하나의 해결책

int get_rotated_name(char *filename,char *rotatedname,size_t len) 
{ 
    int version = 0; 
    int pos = strrchr(filename,'_'); 

    if(pos == -1) 
     return 1; 
    if(isdigit(filename[pos+1])) { 
     version = atoi(&filename[pos+1]; 
     filename[pos] = 0; 
    } 

    version++; 
    snprintf(rotatedname,len,"%s_%d",filename,version); 

    return 0; 
} 
0

항상 파일 이름 문자열에 대해 strtok 활동이 모두 필요한 것은 아닙니다.

  • 어느

    그것을 확인하기 위해 strncmp으로 일정 부분을 비교하거나 계수로 (A sscanf
  • 이 비교를 수행 atoi 또는 sscanf %d
  • 와 파일 번호의 정수를 당겨 정수를 변경 사용 작업 등)
  • 새로운 정수

를 사용 sprintf에 새 이름을 생성

그리고 실제로 전달 된 함수에서 다음 파일 이름을 생성 할 필요가없는 경우 sprintf과 함께 사용되어 다음 파일 이름을 생성하는 상수 문자열과 회전 정수를 유지하면됩니다.
모든 경우에 사용 가능하지 않을 수 있음을 이해합니다.

0

정말로 시퀀스 번호도 회전 하시겠습니까?.

나는 그렇게하지 말고 일련 번호로 파일 이름을 일정하게 유지하면 얼마나 많은 파일이 열렸는지 알 수 있습니다.

매개 변수 파일 이름의 배열을 유지하고 새 파일을 열 때마다 시작 인덱스와 끝 인덱스를 회전하고 시작 인덱스를 증가시킬 수 있습니다.배열이 채워지면 end-index에서 파일을 제거하고 계속 진행합니다.

0

문자열의 끝 부분을 살펴 보았습니다. 숫자 일 경우 숫자가 아닌 문자에 도달 할 때까지 계속 돌아가서 문자열에 추가하고 위치 (p)를 유지합니다.

  • '파일 이름'=> ''
  • 'filename_9'=> '9'
  • '파일 이름-3786'=> '3786'

그때로 변환 것 숫자 n, 비어 있으면 0으로 가정합니다.

필자는 원래 문자열을 p 개까지 취하여 n + 1을 문자열로 변환하고 연결합니다.

  • '파일 이름'=> 'filename2'
  • 'filename_9'=> 'filename_10'
  • '파일 이름-3786'=> '파일 이름-3787'

또한 볼 수 있었다 '', '_', '-'와 같은 p 번째 문자의 분리 문자를 제거한 다음 _와 같은 고정 된 구분 기호를 항상 추가하십시오.