strstr could be used to search for the strings //, / and : that separate the sections of interest. strrchr could be used to find the trailing / that precedes the filename.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *page = "http://host:port/folder1/folder2/file.jpg";
char *slashes = "//";
char *slash = "/";
char *colon = ":";
char *start = NULL;
char *stop = NULL;
char *host = NULL;
char *port = NULL;
char *path = NULL;
char *file = NULL;
size_t span = 0;
if ( ( start = strstr ( page, slashes)) == NULL) {
fputs ( "could not find \"//\"\n", stderr);
return 1;
}
start += strlen ( slashes);//move pointer so the slashes are excluded
if ( ( stop = strstr ( start, colon)) == NULL) {
fputs ( "could not find \":\"\n", stderr);
return 1;
}
span = stop - start;
if ( ( host = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( host, start, span);
host[span] = '\0';
start = stop + strlen ( colon);
if ( ( stop = strstr ( start, slash)) == NULL) {
fputs ( "could not find leading \"/\"\n", stderr);
return 1;
}
span = stop - start;
if ( ( port = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( port, start, span);
port[span] = '\0';
span = strlen ( stop) + 1;
if ( ( path = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( path, stop, span);
path[span] = '\0';
if ( ( start = strrchr ( page, slash[0])) == NULL) {
fputs ( "could not find trailing \"/\"\n", stderr);
return 1;
}
start += strlen ( slash);
span = strlen ( start) + 1;
if ( ( file = malloc ( span)) == NULL) {
fputs ( "malloc failed\n", stderr);
return 1;
}
memmove ( file, start, span);
file[span] = '\0';
puts ( host);
puts ( port);
puts ( path);
puts ( file);
free ( host);
free ( port);
free ( path);
free ( file);
return 0;
}
strcmp()compares strings, not individual characters or parts of strings. RTFM.if (strcmp(&page[i], "/"))can be simplified toif (page[i] == '/')). And can you please make it a little clearer what you want this parser to do? If you wanted to clean things up you could have an array ofchar*and access them through an enum. Anyway, the best thing to do, is to callstrcpyon the pointers current pos - the last pos where you found a slash ( or the begging of the string ).strcmp(&page[i], "/")is not equivalent topage[i] == '/'.