下面的示例将提取子字符串。你的填充的格式应该是这样的:
“男孩”、“女孩”、“汽车”、
请注意,文件字符串应以“,”结尾
int read_file_with_string_tokens() {
char * tocken;
char astring[127];
int current = 0;
int limit;
char *filebuffer = NULL;
FILE *file = fopen("your/file/path/and/name", "r");
if (file != NULL) {
fseek(file, 0L, SEEK_END);
int f_size = ftell(file);
fseek(file, 0L, SEEK_SET);
filebuffer = (char*) malloc(f_size + 2);
if (filebuffer == NULL) {
pclose(file);
free(filebuffer);
return -1;
}
memset(filebuffer, 0, f_size + 2);
if (fgets(filebuffer, f_size + 1, file) == NULL) {
fclose(file);
free(filebuffer);
return -1;
}
fclose(file);
memset(astring, 0, 127);
char *result = NULL;
tocken = strchr(filebuffer, ',');
while (tocken != NULL) {
limit = tocken - filebuffer + 1;
strncpy(astring, &filebuffer[current], limit - current - 1);
printf("%s" , astring);
current = limit;
tocken = strchr(&filebuffer[limit], ',');
memset(astring, 0, 127);
}
free(filebuffer);
}
return 0;
}