C programming + problem with char arrays

Im trying to write some code atm which gets the complete pathname of a folder and strips off references to the parent folders. The end result should be just the name of the folder.

Currently Im able to extract the folder name, however Im getting junk added onto the name as well which is making further processing more difficult.

This is how Im doing it


/*Count number of parent folders*/

for(i=0;str;i++)
{
      if((int)str == (int) '/')
                slash_cnt++;
}

/*Extract name of folder*/

for(i=0;str;i++)
{
	if((int)str == (int) '/')
	{
                 cnt++;
	    if(cnt == slash_cnt)
	    {
		flag=1;
 		pos = i;
	    }
	}

	if( (flag==1) && (i>pos) && (i<strlen(str)) )
		folder[i-pos-1] = str
}	 	

For folder[] (which is the folder whose name I want) I will get something like "myfolder\023\04" when I just want "myfolder".

Im not sure what I could be doing wrong, so help would be appreciated

cheers

Gday all

Ive managed to get it to work now, however this involved replacing the char * with char[] (I was using char pointers beforehand to contain the full path of the folder).

Also Im aware you can reference pointers as if they were an array, so could the problem I was getting in the firstplace be related to the way I was referencing ?

The posted code snippet doesn't declare whether you are using char * or char [] for the variable in question and which one of 'em is that variable. Another approach is to find the end of the complete pathname and then walk backwards stopping at the first slash that comes across. Name of last folder starts one character to the right of the slash.

Did you take a look at the source of basename?
DragonflyBSD has pretty respectable code to browse via CVSweb.
src/usr.bin/basename/basename.c - view - 1.11

Sorry str [i]is the variable in question and I declared it as a pointer.

The declaration is as follows

char *str;

/*char array of 1000 bytes ( 1 kb)*/

char cmd[1000];

str = (char *)malloc(sizeof(cmd));

I referenced *str as an array to simplify access to it's value, so sorry for any confusion.

I didn't spend much time testing this, but I think it'll work fine.

#include <iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char *argv[])
{
string separator="/"; // use standard path separator unless backwards slashes are discovered
if (argc!=2) {cout<<"USAGE: pathname pathname"<<endl<<"RETURNS: foldername, no parent."<<endl; return -1;}
string pathname; pathname=argv[1];
cout<<"input:"<<pathname<<endl;
size_t lastslash=pathname.find_last_of("/");
size_t lastbslash=pathname.find_last_of("\\");
if ((lastslash!=string::npos)&&(lastbslash!=string::npos)) {cout<<"use either \\ or /, but not both"<<endl; return -1;}
if (lastslash==string::npos) {lastslash=lastbslash;separator="\\";}
if (lastslash==string::npos) {cout<<pathname<<endl; return 0;}
if ((lastslash+1)>=pathname.size()) {cout<<"error"<<endl; return -1;}
size_t parentslash=pathname.find_last_of(separator.c_str(),lastslash-1);
cout<<"output..."<<endl;
if (parentslash==string::npos) {cout<<&pathname[lastslash+1]<<endl; return 0;}
if (parentslash==lastslash) {cout<<pathname<<endl; return 0;}
parentslash++;
cout.write(&pathname[parentslash],lastslash-parentslash);
cout<<endl;
return 0;
}

Just a suggestion, but you might want to look at using the strtok() subroutine. It will provide for you that which is separated by your "/", your directory names, and save lots of iterative coding. Tastes great and much less filling.

Very often strtok is recommended for parsing tokens, but it can't accept a literal string, and since it uses a static buffer it can not be re-entrants.

Perhaps an example using strcspn()

/*
 * =====================================================================================
 *
 *       Filename:  delimiters.c
 *
 *    Description:  Parses a directory path string, using the standard C function
 *                  strcspn(). Why I didn't use the strtok() function, you may ask?.
 *                * It modifies the given string, so it can not be a
 *                  literal or constant string 
 *                * It doesn't handle two delimiters back to back correctly.
 *
 *        Version:  1.0
 *        Created:  7/18/2008 11:23:58 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Aia
 *
 * =====================================================================================
 */

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

int main ( void )
{
    const char *path = "/var/log/messages";

    while ( *path )
    {
        size_t len = strcspn( path, "/" ); /* search for delimiter */

        if ( len )
        {
            /*
             * Shows that it works by displaying the resulted token.
             * An array can be use instead to store names
             */
            printf( "\"%.*s\"\n", (int) len, path );
            path += (len + 1); /* jump to next dir/file name */

        }
        else
        {
            /* its the root slash */
            ++path;
            continue;
        }

    }
    return 0;
}