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....
I am not able to debug the cause..... Need help on this,Please guide.
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;
}
Seems to be a problem on line: strncpy(sNewFileName,sTmpFile, (newLen-oneLen));
Feedback: The code formatter is not working correctly on this site for Chrome browser