Reputation: 91
I had this working before, but I was using pointers. getenv() keeps crashing so I copied the results using sprintf(). Now I want to deliminate with : and print only the first occurrence. Please help!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void) {
char buf[999];
const char *token;
// HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8
sprintf(buf, "%s", getenv("HTTP_PROXY"));
*token = strsep(&buf, ":");
printf("New result: %s\n", token);
}
Upvotes: 1
Views: 191
Reputation: 26727
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char const *http_proxy = getenv("HTTP_PROXY");
if (http_proxy == NULL) {
fprintf(stderr, "HTTP_PROXY not set: default 8.8.8.8:8888");
http_proxy = "8.8.8.8:8888";
}
char *cpy = strdup(http_proxy);
char *token = strtok(cpy, ":");
if (token == NULL) {
fprintf(stderr, "wrong format");
return 1;
}
do {
printf("Token: %s\n", token);
} while ((token = strtok(NULL, ":")) != NULL);
free(cpy);
}
Upvotes: 0
Reputation: 726639
Since strsep
wants a pointer to pointer, you must pass a pointer to pointer, not a pointer to array. This is not the same thing; make a pointer, and assign it buf
. Pass a pointer to that new pointer to strsep
to fix the first problem.
The second problem is that since strsep
returns a pointer, you need to assign it to token
, not to *token
:
char buf[999];
const char *token;
// HTTP_PROXY == 8.8.8.8:8888, end result should print 8.8.8.8
sprintf(buf, "%s", getenv("HTTP_PROXY"));
char *ptr = buf; // Since ptr, is a pointer...
token = strsep(&ptr, ":"); // ...you can pass a pointer to pointer
printf("New result: %s\n", token);
Upvotes: 3