473,597 Members | 2,459 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Looking for a library to split pathnames

Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:

-----------------
char *path = "/home/user/Documents/Textdocuments/Bills";
char **dirs;

splitPath(path, dirs);
------------------

`dirs' should then consist of:
dirs[0] == "home"
dirs[1] == "user"
....
dirs[4] == "Bills"

Does anybody know of a function like that?
Thanks for your help.

Sven-Thorsten Fahrbach

P.S.: It could also be a C++ function if there exists a better
equivalent or if it's easier to use. I come from a Perl background and
I'm not that comfortable with string manipulation in C.
Sep 21 '06 #1
22 2916

Sven-Thorsten Fahrbach wrote:
Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:
I suspect someone will be along shortly to say this is Off-Topic :-)

The dirname() and basename() functions on un*x systems will do most of
what you need here.

If this is a homework question (it smells a bit like one), I'd look at
the following questions:-

* how do you work out how many elements are in the pathname?
* how do you allocate space to hold the array of pointers?
* how do you fill the array of pointers?

If you are going to work with C you may as well get to grips with
string handling. It's not _that_ difficult.

Sep 21 '06 #2
ma**********@po box.com wrote:
Sven-Thorsten Fahrbach wrote:
>Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:

I suspect someone will be along shortly to say this is Off-Topic :-)
Oops, sorry. I'm not a regular usenet user ;). I just didn't know where
else to post this.
>
The dirname() and basename() functions on un*x systems will do most of
what you need here.
Thanks, I'll have a look into that!
>
If this is a homework question (it smells a bit like one) [...]
No, it's not, honestly. ;) I'm trying to write a small tool which needs
to do this job. I'd have used Perl but I fear it might be too slow for
my purposes.
I'd look at
the following questions:-

* how do you work out how many elements are in the pathname?
* how do you allocate space to hold the array of pointers?
* how do you fill the array of pointers?

If you are going to work with C you may as well get to grips with
string handling. It's not _that_ difficult.
I know. I just haven't got enough practise. But even though it's not a
homework question it might still be a good exercise!

Thanks for your help!

Sven-Thorsten Fahrbach
Sep 21 '06 #3

Sven-Thorsten Fahrbach wrote:
ma**********@po box.com wrote:
Sven-Thorsten Fahrbach wrote:
Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:
I suspect someone will be along shortly to say this is Off-Topic :-)
Oops, sorry. I'm not a regular usenet user ;). I just didn't know where
else to post this.
If it's about things which are part of the portable C standard, this is
a good place. If it's more platform-specific, somewhere else may be
better (comp.unix.prog rammer?).

However, if we take it as a string handling and memory allocation
exercise, it's probably on-topic :-)

The dirname() and basename() functions on un*x systems will do most of
what you need here.
Thanks, I'll have a look into that!
If this is a homework question (it smells a bit like one) [...]
No, it's not, honestly. ;) I'm trying to write a small tool which needs
to do this job. I'd have used Perl but I fear it might be too slow for
my purposes.
I'd look at
the following questions:-

* how do you work out how many elements are in the pathname?
* how do you allocate space to hold the array of pointers?
* how do you fill the array of pointers?

If you are going to work with C you may as well get to grips with
string handling. It's not _that_ difficult.
I know. I just haven't got enough practise. But even though it's not a
homework question it might still be a good exercise!
OK - I'd count the number of elements by a pass through the string
counting "/" characters, and adjust appropriately for the possibility
of relative pathnames (no leading "/") and a null basename (a trailing
"/"), then malloc() or calloc() the space for the array of pointers.
Depending on whether you want to use a count of paths or have a null
pointer to delimit the array, you may need an extra slot in the array
(I quite like using a null as a delimiter).

Are you clear in your mind how you want to handle relative pathnames
and null basenames, by the way?

Then you could use strtok() - not the nicest function, but it would
work, to walk through the pathname picking out the individual elements
in turn.

Sep 21 '06 #4
Sven-Thorsten Fahrbach wrote:
Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:
I know this isn't _exactly_ what you asked for, but this is what I
generally use:

----------

#include <stdio.h>

int explode( char *str, char delim, char *parts[], int numparts )
{
char *c = str;
int p = 0;

parts[p++] = c;
while ( *c && p < numparts )
{
if ( *c == delim )
{
*c = '\0';
parts[p++] = c+1;
}
c++;
}

return p;
}

int main( int argc, char *argv[] )
{
int p,i;
char *dirs[20];
char path[] = "/home/user/Documents/Textdocuments/Bills";

p = explode( path, '/', dirs, 20 );

for ( i = 0; i < p; i++ )
printf( "%s\n", dirs[i] );

return 0;
}

----------

On the bad side, the string you pass in is changed by the function (all
of the delimiter characters have been set to nil). Also, you must guess
the maximum number of parts in advance. On the plus side, if you do not
mind those limitations, you do not have to deal with dynamic memory
allocation in the explode function.

Most of the time, those limitations are not a problem at all. It works
great as a quick CSV parser (I have a slightly more involved version
that deals with quotes).

Also note that as a path parser, path[0] is returned as an empty
string, since there is nothing before the first delimiter.

--Sean

Sep 21 '06 #5
Sven-Thorsten Fahrbach wrote:
>
Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:

-----------------
char *path = "/home/user/Documents/Textdocuments/Bills";
char **dirs;

splitPath(path, dirs);
------------------

`dirs' should then consist of:
dirs[0] == "home"
dirs[1] == "user"
...
dirs[4] == "Bills"

Does anybody know of a function like that?
The following routine (published here before) should do it. Simply
use '/' as the token delimiter. Wrap it in something that
allocates the memory for dirs[n] to point to. strdup() may come in
handy here. (strdup is non-standard, but available on many
systems, or you can write it yourself).

If you are not worried about re-entrancy and/or altering the
original string, see strtok() (which is standard).

/* ------- file toksplit.h ----------*/
#ifndef H_toksplit_h
# define H_toksplit_h

# ifdef __cplusplus
extern "C" {
# endif

#include <stddef.h>

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh); /* length token can receive */
/* not including final '\0' */

# ifdef __cplusplus
}
# endif
#endif
/* ------- end file toksplit.h ----------*/

/* ------- file toksplit.c ----------*/
#include "toksplit.h "

/* copy over the next token from an input string, after
skipping leading blanks (or other whitespace?). The
token is terminated by the first appearance of tokchar,
or by the end of the source string.

The caller must supply sufficient space in token to
receive any token, Otherwise tokens will be truncated.

Returns: a pointer past the terminating tokchar.

This will happily return an infinity of empty tokens if
called with src pointing to the end of a string. Tokens
will never include a copy of tokchar.

A better name would be "strtkn", except that is reserved
for the system namespace. Change to that at your risk.

released to Public Domain, by C.B. Falconer.
Published 2006-02-20. Attribution appreciated.
Revised 2006-06-13
*/

const char *toksplit(const char *src, /* Source of tokens */
char tokchar, /* token delimiting char */
char *token, /* receiver of parsed token */
size_t lgh) /* length token can receive */
/* not including final '\0' */
{
if (src) {
while (' ' == *src) src++;

while (*src && (tokchar != *src)) {
if (lgh) {
*token++ = *src;
--lgh;
}
src++;
}
if (*src && (tokchar == *src)) src++;
}
*token = '\0';
return src;
} /* toksplit */

#ifdef TESTING
#include <stdio.h>

#define ABRsize 6 /* length of acceptable token abbreviations */

/* ---------------- */

static void showtoken(int i, char *tok)
{
putchar(i + '1'); putchar(':');
puts(tok);
} /* showtoken */

/* ---------------- */

int main(void)
{
char teststring[] = "This is a test, ,, abbrev, more";

const char *t, *s = teststring;
int i;
char token[ABRsize + 1];

puts(teststring );
t = s;
for (i = 0; i < 4; i++) {
t = toksplit(t, ',', token, ABRsize);
showtoken(i, token);
}

puts("\nHow to detect 'no more tokens' while truncating");
t = s; i = 0;
while (*t) {
t = toksplit(t, ',', token, 3);
showtoken(i, token);
i++;
}

puts("\nUsing blanks as token delimiters");
t = s; i = 0;
while (*t) {
t = toksplit(t, ' ', token, ABRsize);
showtoken(i, token);
i++;
}
return 0;
} /* main */

#endif
/* ------- end file toksplit.c ----------*/

--
"The most amazing achievement of the computer software industry
is its continuing cancellation of the steady and staggering
gains made by the computer hardware industry..." - Petroski

--
Posted via a free Usenet account from http://www.teranews.com

Sep 21 '06 #6
"sbaker48" <sb************ **@gmail.comwri tes:
Sven-Thorsten Fahrbach wrote:
>Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:

I know this isn't _exactly_ what you asked for, but this is what I
generally use:

----------

#include <stdio.h>

int explode( char *str, char delim, char *parts[], int numparts ) {
char *c = str;
int p = 0;

parts[p++] = c;
while ( *c && p < numparts ) {
if ( *c == delim ) {
*c = '\0';
parts[p++] = c+1;
}
c++;
}

return p;
}

On the bad side, the string you pass in is changed by the function (all
of the delimiter characters have been set to nil).
Duplicating the string shouldn't be a problem.
Also, you must guess the maximum number of parts in advance.
You can first scan the string and count how many delims are there.
Also note that as a path parser, path[0] is returned as an empty
string, since there is nothing before the first delimiter.
Unless the path is relative. :]

#v+
#include <string.h>

char **explode(char *str, const char *delim, size_t *num) {
size_t capacity = 16, n;
char **arr = malloc(capacity * sizeof *arr);

arr[0] = strtok(str, delim);
while (arr[n]) {
if (++n >= capacity) {
capacity += 16;
arr = (char**)realloc (arr, capacity * sizeof *arr);
}
arr[n] = strtok(0, delim);
}

if (num) *num = n;
return arr;
}
#v-

Returns a NULL terminated array of pointers to each item. In
aditional, if num is not NULL saves there number of elements.
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >--<jid:mina86*jab ber.org>--ooO--(_)--Ooo--
Sep 21 '06 #7
Op Thu, 21 Sep 2006 17:24:28 +0200 schreef Michal Nazarewicz:
"sbaker48" <sb************ **@gmail.comwri tes:
>Sven-Thorsten Fahrbach wrote:
>>Hi

Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:

I know this isn't _exactly_ what you asked for, but this is what I
generally use:

----------

#include <stdio.h>

int explode( char *str, char delim, char *parts[], int numparts ) {
char *c = str;
int p = 0;

parts[p++] = c;
while ( *c && p < numparts ) {
if ( *c == delim ) {
*c = '\0';
parts[p++] = c+1;
}
c++;
}

return p;
}

On the bad side, the string you pass in is changed by the function (all
of the delimiter characters have been set to nil).

Duplicating the string shouldn't be a problem.
>Also, you must guess the maximum number of parts in advance.

You can first scan the string and count how many delims are there.
>Also note that as a path parser, path[0] is returned as an empty
string, since there is nothing before the first delimiter.

Unless the path is relative. :]

#v+
Non-standard directive, <OT>gcc complains</OT>
#include <string.h>

char **explode(char *str, const char *delim, size_t *num) {
size_t capacity = 16, n;
char **arr = malloc(capacity * sizeof *arr);
What if the allocation fails?
>
arr[0] = strtok(str, delim);
while (arr[n]) {
if (++n >= capacity) {
capacity += 16;
arr = (char**)realloc (arr, capacity * sizeof *arr);
arr = realloc(arr, capacity * sizeof *arr);
What if the allocation fails?
}
arr[n] = strtok(0, delim);
}

if (num) *num = n;
return arr;
}
#v-
Non-standard directive, <OT>gcc complains</OT>
--
Coos
Sep 21 '06 #8
Michal Nazarewicz wrote:
"sbaker48" <sb************ **@gmail.comwri tes:
>Sven-Thorsten Fahrbach wrote:
>>>
Does anybody know of a library that offers a function to split
pathnames. It should work somewhat like the following code snippet:
.... snip ...
>
#v+
#include <string.h>

char **explode(char *str, const char *delim, size_t *num) {
size_t capacity = 16, n;
char **arr = malloc(capacity * sizeof *arr);
You failed to test the result of this malloc, so the following
statment may well cause explosions, nasal demons, whatnot.
>
arr[0] = strtok(str, delim);
while (arr[n]) {
if (++n >= capacity) {
capacity += 16;
arr = (char**)realloc (arr, capacity * sizeof *arr);
Very bad code. First, never cast realloc (or malloc). You hid the
error of failing to #include <stdlib.h>. Never capture the result
of realloc in the original pointer, you should use something like:

if (tmp = realloc(arr, newsize)) arr = tmp;
else {
/* out of memory error recovery */
}
}
arr[n] = strtok(0, delim);
}

if (num) *num = n;
return arr;
}
#v-
What in heavens name are the #v+ and #v- for, apart from creating a
syntax error?

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

--
Posted via a free Usenet account from http://www.teranews.com

Sep 21 '06 #9
CBFalconer <cb********@yah oo.comwrites:
Michal Nazarewicz wrote:
> char **arr = malloc(capacity * sizeof *arr);
You failed to test the result of this malloc, so the following
statment may well cause explosions, nasal demons, whatnot.
True, but real operating systems terminates process with SIGSEGV. :P
> arr = (char**)realloc (arr, capacity * sizeof *arr);
Very bad code. First, never cast realloc (or malloc). You hid the
error of failing to #include <stdlib.h>. Never capture the result
of realloc in the original pointer, you should use something like:
True, cast was inserted by mistake.
What in heavens name are the #v+ and #v- for, apart from creating a
syntax error?
They say intelligent news- and mailreaders that the text between is
a source code listing or alike which ought to be displayed with
monospace font.

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl >--<jid:mina86*jab ber.org>--ooO--(_)--Ooo--
Sep 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2268
by: Thomas Rademacher | last post by:
Hallo, my application want to scan WIN directories with UNC pathnames. The methods os.path.isdir(pathname) and os.listdir(pathname) work fine with pathname="\\\\servername\\path". But with the argument pathname="\\\\servername" the method os.path.isdir(pathname) returns 0 and the method os.listdir(pathname) raises an exception.
51
2998
by: Reinhold Birkenfeld | last post by:
Hello, at the moment python-dev is discussing including Jason Orendorff's path module into the standard library. Do you have any other good and valued Python modules that you would think are bug-free, mature (that includes a long release distance) and useful enough to be granted a place in the stdlib? For my part, ctypes seems like a suggestion to start with.
70
4063
by: Michael Hoffman | last post by:
Many of you are familiar with Jason Orendorff's path module <http://www.jorendorff.com/articles/python/path/>, which is frequently recommended here on c.l.p. I submitted an RFE to add it to the Python standard library, and Reinhold Birkenfeld started a discussion on it in python-dev <http://mail.python.org/pipermail/python-dev/2005-June/054438.html>. The upshot of the discussion was that many python-dev'ers wanted path added to the...
12
4029
by: Xah Lee | last post by:
Python Doc Problem Example Quote from: http://docs.python.org/lib/module-os.path.html ---------- split( path) Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If
1
1354
by: draco | last post by:
Hi, Let's say I have a dynamic library libapple.so with a method applemethod() which expects a filename string. I call this method from main() which is in the file foo.c. Now foo.c and apple.so are in different directories, and the user calls foo.c with a relative pathname to the file. My question is how do I make sure that applemethod knows where this file is from the realtive pathname? foo.c:
4
1182
by: JollyK | last post by:
Hello everyone... I have created a user-control that has a fairly complex datagrid (with template columns) which includes localization, custom paging, sorting, filtering, searching, caching, options to add, edit, and delete record, and then enabling and disabling links inside the datagrid based on different conditions. Everything is working fine now. I have hand-coded everything and the total length of my code-behind file is around 1900...
4
1579
by: Jéjé | last post by:
Hi, I have a file which contain 1 pair of values by line like: Name1=Value1 = I nned to store these pair of values in a sortedlist. So the result expected for the 2 samples lines is: Key Value Name1 Value1
10
1804
by: mwt | last post by:
So in a further attempt to learn some Python, I've taken the little Library program (http://groups.google.com/group/comp.lang.python/browse_thread/thread/f6a9ccf1bc136f84) I wrote and added several features to it. Readers now quit when they've read all the books in the Library. Books know how many times they've been read. Best of all, you can now create your own list of books to read! Again, the point of all this is to get used to...
3
2759
by: Phaitour | last post by:
Hi there, I'm working on developing a large Class Library project that is slowly becoming a shared "framework" library amongst multiple applications. As this shared library grows, I need to start thinking about ways to split this library up. In observing the .net framework, I've noticed that each major branch of the framework (eg. System.Net or System.Data) and even some of the minor branches are split up into individual dlls. When...
0
7893
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8040
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8259
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6698
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5436
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3889
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3932
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2408
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.