Quickly Learn To Search And Count Words From A Text File In Modern C++
February 6, 2021 By Yilmaz Yoru
C++ Builder is easy to operate on files on Windows. There are many methods to operate on files. Some of these methods are explained well in Для просмотра ссылки Войдиили Зарегистрируйся.
In this post we create a snippet to search and count a text from a text file.
Now let’s use this in an example
C++ Console Application VCL Example
2. Hit F9 to run with debugging on Console
C++ Console Application FMX Example
2. Hit F9 to run with debugging on Console
This method can be used to modify (replace) text files too. To do this, you need to open another file to write new modified and unmodified lines in order.
February 6, 2021 By Yilmaz Yoru
C++ Builder is easy to operate on files on Windows. There are many methods to operate on files. Some of these methods are explained well in Для просмотра ссылки Войди
In this post we create a snippet to search and count a text from a text file.
C++:
unsigned int count_text(UnicodeString text, UnicodeString filename)
{
if(FileExists(filename))
{
UnicodeString us;
unsigned int count=0;
TStreamReader *SReader = new TStreamReader(filename, TEncoding::UTF8);
do
{
us=SReader->ReadLine();
if(us.Pos(text)>0) count++;
} while(!SReader->EndOfStream);
SReader->Free();
return(count);
}
return(0);
}
C++ Console Application VCL Example
- Create a new C++ Builder Console VCL application, save all project and unit files to a folder. And modify code lines as below;
C++:
#include <vcl.h>#include <stdio.h>
unsigned int count_text(UnicodeString text, UnicodeString filename)
{
if(FileExists(filename))
{
UnicodeString us;
unsigned int count=0;
TStreamReader *SReader = new TStreamReader(filename, TEncoding::UTF8);
do
{
us=SReader->ReadLine();
if(us.Pos(text)>0) count++;
} while(!SReader->EndOfStream);
SReader->Free();
return(count);
}
return(0);
}
int _tmain(int argc, _TCHAR* argv[])
{
printf( "hello = %d\n", count_text(L"hello", L"D:\\test.txt") );
printf( "the = %d\n", count_text(L"the", L"D:\\test.txt") );
getchar();
return 0;
}
2. Hit F9 to run with debugging on Console
C++ Console Application FMX Example
- Create a new C++ Builder Console FMX application, save all project and unit files to a folder. And modify code lines as below;
C++:
#include <fmx.h>
#include <stdio.h>
unsigned int count_text(UnicodeString text, UnicodeString filename)
{
if(FileExists(filename))
{
UnicodeString us;
unsigned int count=0;
TStreamReader *SReader = new TStreamReader(filename, TEncoding::UTF8);
do
{
us=SReader->ReadLine();
if(us.Pos(text)>0) count++;
} while(!SReader->EndOfStream);
return(count);
}
return(0);
}
int _tmain(int argc, _TCHAR* argv[])
{
printf( "hello = %d\n", count_text(L"hello", L"D:\\test.txt") );
printf( "the = %d\n", count_text(L"the", L"D:\\test.txt") );
getchar();
return 0;
}
This method can be used to modify (replace) text files too. To do this, you need to open another file to write new modified and unmodified lines in order.