1

I want to split this txt file. How can I split it from semicolons? It must be in C.

x.txt:

stack;can;3232112233;asdasdasdasd

Result

string[0]=stack
string[1]=can

etc.

droidmachine
  • 577
  • 2
  • 8
  • 24

2 Answers2

3

See this example:

#include <stdio.h>
#include <string.h>

int main(void) {

    int j, i=0; // used to iterate through array

    char userInput[81], *token[80]; //user input and array to hold max possible tokens, aka 80.

    printf("Enter a line of text to be tokenized: ");
    fgets(userInput, sizeof(userInput), stdin);

    token[0] = strtok(userInput, ";"); //get pointer to first token found and store in 0
                                       //place in array
    while(token[i]!= NULL) {   //ensure a pointer was found
        i++;
        token[i] = strtok(NULL, " "); //continue to tokenize the string
    }

    for(j = 0; j <= i-1; j++) {
        printf("%s\n", token[j]); //print out all of the tokens
    }

    return 0;
}
Stian
  • 1,261
  • 2
  • 19
  • 38
1

Read complete file into a buffer using fread and then use strtok with ; as a delimiter and keep saving your strings.

Community
  • 1
  • 1
Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125