1. 字符串分割函数strtok,其中一个用途是可以用来读取配置文件中的内容,程序启动时把相应参数进行初始化.
2.源程序
/* yang.txt 中内容为*/
/*wo shi shei?
nSta = , 5 */
FILE *fp;
char strLine[513];
char *ptr;
CString str,tmpStr;
char *token;
char *seps = " ,///=/n";
memset(strLine,0,sizeof(strLine));
if( (fp = fopen("yang.txt","r") ) != NULL)
{
while( !feof(fp))
{
ptr = fgets(strLine,512,fp);
if( ptr == NULL)
{
continue;
}
while( (*ptr == ' ') || (*ptr == '/t'))
ptr++;
if( *ptr == '#' || *ptr == 0 || *ptr == '/n')
continue;
token = strtok(ptr,seps);
while( token != NULL)
{
tmpStr = token;
str += tmpStr;
str += "/n";
token = strtok(NULL,seps);// 第二次调用时第一参数为NULL
}
}
AfxMessageBox(str);
// str 为:
// wo
// shi
// shei?
// nSta
// 5
3.strtok函数说明: (from msdn)
1)char *strtok( char *strToken, const char *strDelimit );
2)Parameters
strToken: 包含tokens的字符串
strDelimit: 包含所有分隔符字符的字符串
3) function:
根据strDelimit中的字符来分割字符串 strToken,以下时msdn的描述:
The strtok function finds the next token in strToken. The set of characters in strDelimit specifies possible delimiters of the token to be found in strToken on the current call.
On the first call to strtok, the function skips leading delimiters and returns a pointer to the first token in strToken, terminating the token with a null character. More tokens can be broken out of the remainder of strToken by a series of calls to strtok. Each call to strtok modifies strToken by inserting a null character after the token returned by that call. To read the next token from strToken, call strtok with a NULL value for the strToken argument. The NULL strToken argument causes strtok to search for the next token in the modified strToken. The strDelimit argument can take any value from one call to the next so that the set of delimiters may vary.
4) 说明:
字符串不可再分时,即查找不到新的token时返回NULL;否则返回分隔符前的字符串指针.
第一次调用strok时,自动去除掉最前面的分隔符.
4 fgets函数
fgets(char * str,int nLen,FILE *fp);
从文件中读取nLen-1个字符到str中.
读取出错时返回NULL
遇到/n或读取到的字符串的个数为nLen-1个时,返回值为读取到的字符串的首地址,内容同str.