I have a bit of code and I need to split the words in the filename and store them separately.
Example:
Input -> filename ( e.g. /Users/user/Documents/uni
)
Storage in variable/array as separate words ( not sure how):
char array/struct array = Users user Documents uni
How can I achieve the above example of storing words with C?
Here is my code:
int main(int argc, char *argv[])
{
char filename[255];
for (int i = 0; i < argc; i )
{
strcpy(&filename[i], argv[i]);
}
}
Thanks in advance
CodePudding user response:
Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char filename[BUFSIZ]; // pathname
int i;
int n = 0; // number of words
char **ary = NULL; // array of strings
char *tok; // pointer to each token
if (argc != 2) { // verify aruguments
fprintf(stderr, "usage: %s pathname\n", argv[0]);
exit(1);
}
strncpy(filename, argv[1], BUFSIZ);
for (tok = strtok(filename, "/"); tok != NULL; tok = strtok(NULL, "/")) {
if (NULL == (ary = realloc(ary, (n 1) * sizeof(*ary)))) {
// enlarge array of strings
perror("realloc");
exit(1);
}
if (NULL == (ary[n] = malloc(strlen(tok) 1))) {
// allocate memory for the word
perror("malloc");
exit(1);
}
strncpy(ary[n], tok, strlen(tok) 1);
// copy the token to the array
n ;
}
// see the results
for (i = 0; i < n; i ) {
printf("[%d] %s\n", i, ary[i]);
}
// free the allocated memory
for (i = 0; i < n; i ) {
free(ary[i]);
}
free(ary);
return 0;
}
If you compile the code to the executable a.out
, the outout will look like:
$ ./a.out /Users/user/Documents/uni
[0] Users
[1] user
[2] Documents
[3] uni
CodePudding user response:
I have managed to achieve the desired outcome with this piece of code:
int main(int argc, char *argv[])
{
char word[255];
const char s[2] = "/";
char *token;
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
strcpy(word, argv[0]);
token = strtok(word, s);
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
}