Using realloc to increase array size, adding values backwards?

Status
Not open for further replies.
I am trying to write a complicated function as part of a file system program I am writing.(Well, complicated for me anyway). Because a user can specify a filename as either a relative path or an absolute path, it was recommended that I always use filenames as absolute paths, hence I am trying to write a build_absolute path function.

For example, if someone writes "myfile.txt", I need to locate all of the parent directories up to the root, and store the absolute path name in a string. So the absolute path would then be stored like:

/parent/parent/myfile.txt

My professor recommended using realloc to increase the size of the name array, and I think I understand that. My problem is as I go up the directory tree and get the names of the parents, how do I add them to the front of the array? strcat woul add it to the end, is there a function that will basically concatenate the new string to the front of the old one? Or is there a good way to go about this?

I understand everything about the assignment except this one part, and this is keeping me from going forward. If anyone could give me some advice, I would greatly appreciate it.
 

YakDaGringo

Ars Tribunus Militum
1,739
Well, if you're messing with realloc(), you're programming in C or you're a masochist. Why not create a linked list of values like this:

file<-parent0<-parent1...<-parentn<-root

then parse it back through into a string? Size isn't really a concern, speed won't be affected profoundly since this can all fit in the cache, it fits easily into a simple loop, and you can use functions you know (strcat()) to create the absolute path.

It's not very pretty, but it's probably the easiest way to do it.
 

YakDaGringo

Ars Tribunus Militum
1,739
Oooh! I like that. ^^^

It's cool, but you're doing a character-by-character reversal twice for each string, so you're reversing it twice; once per directory/file and again for the whole string. This is all in the cache, so it's quick, but you're still burning more cycles than some pointer voodoo would. Another advantage to the linked list is that it gives you an opportunity to free() all the memory you just allocated, unless you're planning on doing everything on the stack. You'd also get to return the string with a series of recursive calls to strcat(). :p

Then again, I'm sure there's a call to the system to return the path to the file... you could also reconstruct it from environment variables, but I don't even want to think about doing that in C.
 
Status
Not open for further replies.