需求
从文本文件中逐行读取内容,并对读取到的每一行数据字符串进行分割
比如某一行数据字符串为“strtok function testing” 按空格进行分割,
则需返回的结果是“strtok”,“function”,“testing”三个单词
代码实现
#include "stdafx.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int _tmain(int argc, _TCHAR* argv[])
{
//char input[64] = {" sfsf n8784b55632656 6525 558456 5222 "};
char strBuffer[128] = {0};
char *pStr = NULL;
FILE *hFile = NULL;
hFile = fopen("stringfile.txt", "rb");
if(NULL == hFile)
{
printf("open file failed\n");
return 0;
}
while(fgets(strBuffer, sizeof(strBuffer), hFile) != NULL)//逐行读取文件的数据
{
pStr = strtok(strBuffer," ");//按空格进行分割
while(pStr)
{
printf("string: %s\n",pStr);
pStr = strtok(NULL," ");//按空格进行循环分割获取所有字符串
}
}
if(hFile)
{
fclose(hFile);
hFile = NULL;
}
system("pause");
return 0;
}