number of characters in file
Hallo.
As you have seen I have problems with wchar_t char and so on... because I have allways works with MFC and Cstring.
So I Dont know exactly, how to get textdata out of a file.
ifstream ofOut;
// Open the file.
ofOut.open(str);
// get all Data out of File
char * output = (char *)malloc( NUMBER_OF_CHARACTERS_IN_FILE);
ofOut >> output;
wchar_t * converted;
mbstowcs(converted , output , NUMBER_OF_CHARACTERS_IN_FILE);
// Close file
ofOut.close();
So how do I find out, how many characters are in this File?
Thanks for help.
MD
# 1 Re: number of characters in file
You can use a comboination of tellg()/seekg() for a completely
portable solution. here is also a stat() function that is supported
in all major compilers. Note: open the file binary and use read()
not operator >>. (The following does not append a trailing
NULL).
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
std::ifstream in("p.cpp",std::ios::binary);
if (!in)
{
std::cout << "problem with file open" << std::endl;
return 0;
}
in.seekg(0,std::ios::end);
unsigned long length = in.tellg();
in.seekg(0,std::ios::beg);
char *szFileText = new char[length];
in.read(szFileText,length);
// when done
delete [] szFileText;
return 0;
}
# 2 Re: number of characters in file
If this is a text file, wouldn't it just be:
[Number of Characters] = [Size of File] / [Size of TCHAR]
HANDLE hFile = CreateFile(szFileName, NULL, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD dwChars = GetFileSize(hFile, NULL) / sizeof(TCHAR);
CloseHandle(hFile);
}
Bond at 2007-11-11 1:13:21 >

# 3 Re: number of characters in file
Originally posted by Bond
If this is a text file, wouldn't it just be:
[Number of Characters] = [Size of File] / [Size of TCHAR]
Yes, if you are sure that the text-file you are reading is a Unicode text file.
Normally a Unicode textfile has a Unicode BOM (Byte Order Mark) at the beginning of the file to tell you if this text-file is Unicode and in which byte order the 16 bits of each character are saved.
Marc G at 2007-11-11 1:14:20 >

# 4 Re: number of characters in file
Mm, in your case:
char * output = (char *)malloc(NUMBER_OF_CHARACTERS_IN_FILE);
you are allocating a char, so you need to allocate the number of BYTES in your file, not the number of characters.
Marc G at 2007-11-11 1:15:15 >
