strtok() 函数实现字符串分割
实例代码:
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv)
{
char test[] = "hello world c!!";
char ch[] = " ";
char * ptr = strtok(test, ch); // 实现字符串的分割
while(ptr != NULL)
{
printf("%s\n", ptr);
ptr = strtok(NULL, ch);
}
return 0;
}
例子:
int is_comment(char * content)
{
int i = 0;
int len = strlen(content);
while(i < len && isspace(content[i]) != 0)
{
++i;
}
if(i >= len || content[i] == '#') // empty line or comment line
return 0;
else
return 1;
}
int open(FILE ** f)
{
char *filename = "key.conf";
if((*f = fopen(filename, "rw")) == NULL)
{
// no such file
return ENOENT;
}
else
{
return 0;
}
}
int close(FILE **f)
{
return fclose(*f);
}
int read_id(FILE *f)
{
char content[MAX_LENGTH];
char *id = NULL;
while(!feof(f))
{
fgets(content, MAX_LENGTH, f);
content[strlen(content) - 2] ='\0';
if(0 != is_comment(content))
{
id = strtok(content, " ");
if(id != NULL)
{
printf("%s\n", id);
}
else
return -1;
}
}
return 0;
}
int read_key(FILE *f)
{
char content[MAX_LENGTH];
char *key;
while(!feof(f))
{
fgets(content, MAX_LENGTH, f);
content[strlen(content) - 2] ='\0';
if(0 != is_comment(content))
{
key = strtok(content, " ");
if(key != NULL)
{
key = strtok(NULL, " ");
if(key != NULL)
{
printf("%s\n", key);
}
else
return -1;
}
else
return -1;
}
}
return 0;
}
int read_uuid(FILE *f)
{
char content[MAX_LENGTH];
char *uuid;
while(!feof(f))
{
fgets(content, MAX_LENGTH, f);
content[strlen(content) - 2] ='\0';
if(0 != is_comment(content))
{
uuid = strtok(content, " ");
if(uuid != NULL)
{
uuid = strtok(NULL, " ");
if(uuid != NULL)
{
uuid = strtok(NULL, " ");
if(uuid != NULL)
{
printf("%s\n", uuid);
}
}
else
return -1;
}
else
return -1;
}
}
return 0;
}
int main(int argc, char ** argv)
{
FILE *f = NULL;
open(&f);
//printf("space = %d\n", isspace(' '));
read_id(f);
fseek(f,0,0);
read_key(f);
fseek(f,0,0);
read_uuid(f);
close(&f);
return 0;
}
## comment: start with '#'
## style: plain text
## format: <unique-identifier> <encrypted-key> [uuid,...]
## uuid has upper limit for one key, the upper limit is 10
10000001 asdfgh123456i719 550E8400-E29B-11D4-A716-446655440000
10000002 asdfgh123456i710
10000003 asdfgh123456i711 550E8400-E29B-11D4-A716-44665544asdf
10000004 asdfgh123456i712
10000005 asdfgh123456i713 550E8400-E29B-11D4-A716-44665544asdf,550E8400-E29B-11D4-A716-446655440987
# end