如何在C中拆分包含; s的文本文件?

时间:2012-04-22 18:51:43

标签: c

我想拆分这个txt文件。我如何将它从分号中分离出来?它必须在C中。

x.txt:

stack;can;3232112233;asdasdasdasd

结果

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

2 个答案:

答案 0 :(得分:3)

见这个例子:

#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;
}

答案 1 :(得分:1)

使用fread将完整文件读入缓冲区,然后将strtok;一起用作分隔符并继续保存字符串。