C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 01-15-2009, 06:18 AM   #1
Registered User
 
Join Date: Jan 2009
Posts: 3
extracting a specific part out of a string (errors in my code?)

Hello guys,

I have the following task to do:

given a string (char * buf) in a specific way ("putfile $[path of file]") I want to extract the filename out of the filepath with a function called extract_name.

Here's the code:

Code:
char* extract_name(char* buf){
	int length = strlen(buf)-1;
	int count  = -1;
	int i = 0;
	char * fname;
	char c;
	for(i = length; i>=0; i--){	//go backwards through string to gain knowledge of filename length
		c = buf[length];
		if((c == '/') || (c == '\\') || (c == '$')){ //either of these chars show me I have reached the
													 //beginning of my filename, so I leave the loop
			break;
		}
		count++;
		length--;
	}
	fname = (char*)calloc(count+1, sizeof(char));	//allocate free space
	fname[count+1] = '\0';							//put string termination symbol
	length = strlen(buf)-1;							//reset length
	
	for(i = count; i>=0; i--){						//go backwards through string
		fname[i] = buf[length];						//and set the characters accordingly
		i--;
		length--;
	}
	return fname;									//return pointer to name
}
Now, my problem is, that I get no filename back. It's just empty.

Maybe you need to see this part of code too?

Code:
        char *name;
        name = extract_name(message);
	path  = (char*)calloc(10 + strlen(act_user->username) + strlen(name), sizeof(char)); 
									
									
	sprintf(path, "./uploads/%s/%s",act_user->username,name); //create  path-string
Anyone can tell me where exactly my error is? Or should I do it in a different way alltogether?
snpnx is offline   Reply With Quote
Old 01-15-2009, 06:29 AM   #2
Woof, woof!
 
zacs7's Avatar
 
Join Date: Mar 2007
Location: Australia
Posts: 3,139
Yarr ugly!

Code:
#include <stdio.h>
#include <stdlib.h> 

#define MAX_PATH 256

char * extract_name(char * buf)
{
   char * path = NULL;

   path = malloc(MAX_PATH);
   if(!path)
      return NULL;

   sscanf(buf, "%*s %256s", path);

   return path; 
}

int main(void)
{
   char * a;

   a = extract_name("putfile /foo/bar");
   if(a)
   {
      printf("%s\n", a);
      free(a);
   }
   
   return 0;
}
I haven't done the work for you either. It's an ugly solution, you can do it your way and write a far nicer one. Also don't cast calloc().

1. You don't need to traverse backwards. You know the length of the filename is the length of the buffer - the start bit.
2. You can use strncpy() you know .

In reality I'd probably strip all the trailing and leading spaces from the buffer, then again from the path after I parsed it. Probably with the above method if I was feeling lazy
__________________
"I.T. gets the chicky-babes" - M. Kelly
bakefile | vim

Last edited by zacs7; 01-15-2009 at 06:34 AM.
zacs7 is offline   Reply With Quote
Old 01-15-2009, 06:37 AM   #3
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,946
You should be aware of strrchr:
Code:
#include <stdio.h>
#include <string.h>

char *extract_name (char *fpathname) {
	char *ptr=strrchr(fpathname,'/');
	ptr++;
	return ptr;
}


int main() {
	char example[]="/home/user/somedir/afile.o",
		*shortname=extract_name(example);
	printf("%s\n",shortname);
}
BE AWARE THAT THIS RETURNS ONLY A POINTER INTO THE ORIGINAL STRING. However, it does work and demonstrate strrchr, which you need to look up.
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS

Last edited by MK27; 01-15-2009 at 06:44 AM.
MK27 is online now   Reply With Quote
Old 01-15-2009, 06:40 AM   #4
Woof, woof!
 
zacs7's Avatar
 
Join Date: Mar 2007
Location: Australia
Posts: 3,139
Yes, but "./foo/bar" isn't the same as "/foo/bar" nor is "../foo/bar":-)
__________________
"I.T. gets the chicky-babes" - M. Kelly
bakefile | vim
zacs7 is offline   Reply With Quote
Old 01-15-2009, 06:47 AM   #5
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,946
I really don't think you should do this:

Quote:
Originally Posted by snpnx View Post
if((c == '/') || (c == '\\') || (c == '$')){ //either of these chars show me I have
If portability is a factor use an ifdef statement:
Code:
#ifdef WIN32
#define SC 92     /* a "\"   */
#else 
#define SC 47     /* a  "/" */
#endif
[...]
char *ptr=strrchr(fpathname,SC);
ps. an honest question -- what OS allows "$" in filenames or paths?
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is online now   Reply With Quote
Old 01-15-2009, 06:48 AM   #6
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,946
Quote:
Originally Posted by zacs7 View Post
Yes, but "./foo/bar" isn't the same as "/foo/bar" nor is "../foo/bar":-)
Well, that's true. Also, blue is not the same as green. Is this relevent?
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is online now   Reply With Quote
Old 01-15-2009, 06:57 AM   #7
Registered User
 
Join Date: Jan 2009
Posts: 3
@zacs7: why no use of calloc?

@MK27: an honest question -- what OS allows "$" in filenames or paths?

Not a question of the OS, it was just needed since I did go backwards through the String and thought if the user puts in the filename without any leading './' I know it's right after the '$'. But I'll use strrchr, which I didn't know and let the user know that he needs to give me a '/' with the filename.


@all
Thanks for your help, it should be enough for me to figure it out. If I have questions again, I'll come back
snpnx is offline   Reply With Quote
Old 01-15-2009, 06:58 AM   #8
Woof, woof!
 
zacs7's Avatar
 
Join Date: Mar 2007
Location: Australia
Posts: 3,139
> ps. an honest question -- what OS allows "$" in filenames or paths?
The ext2/3 filesystems. So Linux :-)
__________________
"I.T. gets the chicky-babes" - M. Kelly
bakefile | vim
zacs7 is offline   Reply With Quote
Old 01-15-2009, 06:59 AM   #9
Woof, woof!
 
zacs7's Avatar
 
Join Date: Mar 2007
Location: Australia
Posts: 3,139
I said don't cast calloc(). See the FAQ.
__________________
"I.T. gets the chicky-babes" - M. Kelly
bakefile | vim
zacs7 is offline   Reply With Quote
Old 01-15-2009, 07:13 AM   #10
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,946
Quote:
Originally Posted by snpnx View Post
Not a question of the OS, it was just needed since I did go backwards through the String and thought if the user puts in the filename without any leading './' I know it's right after the '$'. But I'll use strrchr, which I didn't know and let the user know that he needs to give me a '/' with the filename.
So you mean the end of the command prompt. That WILL NOT be in your string. Also, if the string does not contain any slashes, it is not a path and sticking one on the front won't change that. This is like saying I can make an apple out of an orange by putting a hat on it.

Pick, pick pick...anyway good luck
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is online now   Reply With Quote
Old 01-15-2009, 07:21 AM   #11
Kernel hacker
 
Join Date: Jul 2007
Location: Farncombe, Surrey, England
Posts: 15,686
Code:
	for(i = count; i>=0; i--){						//go backwards through string
		fname[i] = buf[length];						//and set the characters accordingly
		i--;
		length--;
	}
Code in red does what??

Code:
	fname = (char*)calloc(count+1, sizeof(char));	//allocate free space
	fname[count+1] = '\0';							//put string termination symbol
Probably should not access outside of the member you have allocated - it tends to cause bad things to happen. Remember, an n-element array has valid a valid index range of 0 .. (n-1).

--
Mats
__________________
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
matsp is offline   Reply With Quote
Old 01-15-2009, 09:56 AM   #12
Registered User
 
Join Date: Jan 2009
Posts: 3
Quote:
Originally Posted by matsp View Post
Code:
	for(i = count; i>=0; i--){						//go backwards through string
		fname[i] = buf[length];						//and set the characters accordingly
		i--;
		length--;
	}
The code in red was an error, I did it with a while loop before and forgot to take out the decrement.

Quote:
Code:
	fname = (char*)calloc(count+1, sizeof(char));	//allocate free space
	fname[count+1] = '\0';							//put string termination symbol
Probably should not access outside of the member you have allocated - it tends to cause bad things to happen. Remember, an n-element array has valid a valid index range of 0 .. (n-1).

--
Mats
Right, you should not access outside of the allocation, I dunno why I didn't see that O_o
snpnx is offline   Reply With Quote
Old 01-15-2009, 10:04 AM   #13
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,946
Quote:
Originally Posted by zacs7 View Post
> ps. an honest question -- what OS allows "$" in filenames or paths?
The ext2/3 filesystems. So Linux :-)
Okay, $ is allowed in a filename as long as it's not the first character (eg. the$.file) but in this:
Code:
prompt$ /home/user/file.txt
$ is not part of the filename or path.
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is online now   Reply With Quote
Reply

Tags
char, extract, pointer, string

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Error in Recursive String Palindrome Code clegs C Programming 13 12-21-2008 12:36 PM
Binary Search Trees Part III Prelude A Brief History of Cprogramming.com 16 10-02-2004 03:00 PM
Can someone help me understand this example program Guti14 C Programming 6 09-06-2004 12:19 PM
Linked List Help CJ7Mudrover C Programming 9 03-10-2004 10:33 PM
True ASM vs. Fake ASM ???? DavidP A Brief History of Cprogramming.com 7 04-02-2003 04:28 AM


All times are GMT -6. The time now is 09:10 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22