Code:
#include <string>
using std::string;
#include <cstring>
#include <cstdlib>
#include <windows.h>
#define MAX_TOKENS 5
int main()
{
HANDLE hFile;
DWORD dwSize,dwReadSize;
char *lpBuffer = 0,
*strPtr, //A pointer which is the return of strtok()
*strP1[MAX_TOKENS];//Buffers as array of 2 pointers
int x = 0;
string sResult;
hFile = CreateFile("text.txt",GENERIC_READ,0, NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL); //Open File for reading
if(!hFile){
MessageBox(0,"Error with file","Error",MB_OK);
exit(0);
}
dwSize = GetFileSize(hFile,NULL);//Get the size of the file
lpBuffer = (char*)GlobalAlloc(0,dwSize+1); //Create a read in buffer
if(!lpBuffer){
MessageBox(0,"Error with memory allocation","Error",MB_OK);
CloseHandle(hFile);
exit(0);
}
ReadFile(hFile,lpBuffer,dwSize + 1,&dwReadSize,NULL);//Suck up file contents to buffer
lpBuffer[(int)dwSize] = '\0';//NULL terminate
char strcopy[(int)dwSize +1];//A copy to stop original info being chewed up
strcpy(strcopy,lpBuffer); //make copy to tokenize
strPtr = strtok(strcopy,"\n");//Set Strtok to beginning of strcopy. Use '\n' for delimiter
while(strPtr && x < MAX_TOKENS){//while token is not NULL and less than total tokens
strP1[x] = new char[100]; //Create space dynamically
strcpy(strP1[x],strPtr);//Copy token into buffer array
strPtr = strtok(NULL,"\n");//Force strtok up the string
x++;
}
for(int y = 0;y<x;y++){
sResult += "Found token - ";
sResult += strP1[y];
sResult += "\n";
delete strP1[y]; //Clean up after myself
//SetDlgText().......
}
MessageBox(0,sResult.c_str(),"Results",MB_OK);
GlobalFree(lpBuffer);//free memory
CloseHandle(hFile);//close file
return 0;
}
This fits in with what you were asking a while ago on strtok().
I reused the code I gave ,but read from a file and used '\n' as the token delimiter instead of space....
The code sucks up the contents of a file called "text.txt", makes a copy and then tokenises it.
I used some windows funcs CreateFile() & GlobalAlloc() cuz I am trying to get used to using them . Also I used the string class cuz its so easy to use.