-
Character in a String
I'm trying to make a function that turns a filename into a shorter name. For example "c:\windows\clouds.bmp" to "clouds". The problem comes at sname[s]=c; Does anyone know what the problem is? I have no idea. It doesn't give me a compliler error, but I get an assembly error (I use borland).
Code:
void ShortenFileName(char fname[0xff], char sname[0xff]) {
int f=0, s=0;
char c;
do {
c = fname[f];
if (c=='.' || c=='\0') {
sname[s]='\0';
return;
}
sname[s]=c;
s++;
if (c=='\\') {
s=0;
}
}
while(true);
}
-
I would do
Code:
void ShortenFileName(char *fname, char *sname)
{
int iIndex=0;
while((fname[iIndex] != '.' )&&( fname[iIndex] != '\0' ))
{
sname[iIndex]=fname[iIndex];
iIndex++;
}
sname[iIndex]='\0';
return;
}
or
Code:
void ShortenFileName(char *fname, char *sname)
{
char *pString=NULL,*pLastSlash=NULL;
//find the first \
pString=strstr(fname,"\");
if(pString!=NULL)//found one look for more
{
do
{
pLastSlash=pString;
pString=strstr(pString,"\");
}
while(pString!=NULL)
pLastSlash++; //now should be just after last back slash
}
else pLastSlash=fname[0]; //no back slash so set to start
pString=sname[0];
while(pLastSlash != '.' )&&( pLastSlash != '\0' ))
{
*pString++=*pLastSlash++;
}
return;
}
(or something on these lines, I have not tested this)
-
Remember that you must write '\\' instead of '\'.
-
why...
So why won't it let me use sname[s]=c;
Why do you increment the pointers? (*pString++=*pLastSlash++;)
-
The pointers are incremented so one string is copied into the other and the while has something new to test. They are just an index to each string.
I think that you need to use a pointer if trying to make an element of a string array = another char variable.
Or
as the char not terminated may read past the single character into the next memory location. (treats the char "c" as an array ie string)
-
I used the function you gave me, and it gave me the same type of error, not in compiling but in debugging. it gave me it where you incremented both pointers.