PDA

View Full Version : C - How to remove end of string...


shwaip
24 Mar 2004, 8:08am
For one of my classes, we need to write a shell to access information on a floppy, and implement several commands (ls, cp, etc.)

I need help with the following:

the current directory is stored in memory, pointed to by the global variable CURRENT_DIRECTORY, and one of the things I am doing requires me to truncate it:

ex:

//at very top of code

char* CURRENT_DIRECTORY;
//later on, space is allocated

(value of CURRENT_DIRECTORY)
/DIR1/DIR2/DIR3

I want to remove "/DIR3", leaving CURRENT_DIRECTORY pointing to /DIR1/DIR2

it is fine if CURRENT_DIRECTORY points to /DIR1/DIR2\0 (string termination char)

thx

hypermood
24 Mar 2004, 1:22pm
char *temp = &CURRENT_DIRECTORY[strlen(CURRENT_DIRECTORY)];

while (temp > CURRENT_DIRECTORY && *temp != '/')
temp--;

if (*temp == '/')
temp = '\0';

Geeky1
24 Mar 2004, 3:40pm
Shift the '\0' over to the end of 'dir2'. The best way to do this is using the code hypermood posted already.

shwaip
24 Mar 2004, 5:52pm
I tried it, and it doesn't do anything. It keeps the CURRENT_DIRECTORY exactly the same.

got it, it needed this:

*temp = '\0';

a2jfreak
24 Mar 2004, 8:44pm
use the libs, that's what they're there for.

CURRENT_DIRECTORY = strreplace(CURRENT_DIRECTORY, "/DIR3", "");

hypermood
24 Mar 2004, 9:09pm
use the libs, that's what they're there for.

CURRENT_DIRECTORY = strreplace(CURRENT_DIRECTORY, "/DIR3", "");

This only works if you assume that a directory with the same name cannot precede the one at the end.

a2jfreak
24 Mar 2004, 9:43pm
He doesn't want /DIR3, so if the CURRENT_DIRECTORY stored were:
"/DIR1/DIR3/DIR2/DIR3" do you think he would want "/DIR1/DIR3/DIR2" or "/DIR1/DIR2" to be the new string? I'm guessing the latter.

shwaip
24 Mar 2004, 9:57pm
I'd want the former...thx for the suggestion tho a2j