Page 1 of 1

stdio - Path normalization

Posted: Mon Sep 25, 2006 6:00 am
by evilo
Hi,

I wanted to add a normalization function in stdio.c

Code: Select all

 /* Normalize a pathname by removing
  . and .. components, duplicated /, etc. */
char* __ps2_normalize_path(char *path_name)
{
	int i, j;
	int first, next;
	static char out[255];
	
	/* First copy the path into our temp buffer */
	strcpy(out, path_name);
        /* Then append "/" to make the rest easier */
	strcat(out,"/");

	/* Convert "//" to "/" */
	for(i=0; out[i+1]; i++) {
		if(out[i]=='/' && out[i+1]=='/') {
			for(j=i+1; out[j]; j++)
				out[j] = out[j+1];
			i--;
		}
	}

	/* Convert "/./" to "/" */
	for(i=0; out[i] && out[i+1] && out[i+2]; i++) {
		if(out[i]=='/' && out[i+1]=='.' && out[i+2]=='/') {
			for(j=i+1; out[j]; j++)
				out[j] = out[j+2];
			i--;
		}
	}

	/* Convert "/path/../" to "/" until we can't anymore.  Also
	 * convert leading "/../" to "/" */
	first = next = 0;
	while(1) {
		/* If a "../" follows, remove it and the parent */
		if(out[next+1] && out[next+1]=='.' && 
		   out[next+2] && out[next+2]=='.' &&
		   out[next+3] && out[next+3]=='/') {
			for(j=0; out[first+j+1]; j++)
				out[first+j+1] = out[next+j+4];
			first = next = 0;
			continue;
		}

		/* Find next slash */
		first = next;
		for(next=first+1; out[next] && out[next] != '/'; next++)
			continue;
		if(!out[next]) break;
	}

	/* Remove trailing "/" */
	for(i=1; out[i]; i++)
		continue;
	if(i >= 1 && out[i-1] == '/') 
		out[i-1] = 0;

	return (char*)out;
}

the function is greatly inspired by the one present in the pspsdk, so credits is for the orginal authors.

I wanted to call it from the fopen function :

Code: Select all

 if &#40;i < _NFILE&#41; &#123;
        char * t_fname = __ps2_normalize_path&#40;&#40;char *&#41;fname&#41;;
	char b_fname&#91;FILENAME_MAX&#93;;
        __iob&#91;i&#93;.type = __stdio_get_fd_type&#40;fname&#41;;
any comments ?

Posted: Tue Oct 10, 2006 11:36 pm
by evilo
If no ones has comments on this, then I will commit it in the SVN

thank you.

Posted: Wed Nov 22, 2006 4:04 pm
by Herben
keep in mind that the official CDVDMAN cdrom: FS will not accept '/' for a delimiter. CDVDMAN will only accept '\'

Posted: Mon Nov 27, 2006 12:10 am
by evilo
Yes I know, but since i'm not using it in my current project, and since it doesn't change "CDVD" path, I think I will keep it as it for now, and commit it in the current state.