Hi,

Here's my situation.I'm reading a file that consists of characters including white space.Once I read them I'm counting the occurrences of each character.This means I need to count occurrences of white space as well.If I use ifstream I skip the white spaces and I dunno the filesize so I cant use getline.What do I do?

getline() will get an entire line, including white spaces.

ifstream in("filename");
std::string line;
int counter = 0;
while( getline(in,line) )
{
    counter += line.length();
}

but I'm reading a variety of files like pdf's images etc...I'm then encoding the files...so I need to get counts of each character in the file..and then make some modifications...would getline help me?

pdf's and images are not text files, so they have to be opened in binary mode. For them you will have to use the stream's read() function. getline() is of no value to binary files.

If you just want the file size (which is a count of every byte in the file), just seek to the end of the file and get the file position.

ifstream in("filename", ios::binary);
in.seekp(0, ios::end);
int file_size = in.tellg();

I want to count the occurrence of each character in the file.Thanks for your help.

binary files do not contain characters as such, and attempting to count them in binary files is meaningless. But nonetheless, you can use stream's get() function to read the file one byte at a time. Just be aware that binary files contain lots of unreadable bytes.

This article has been dead for over six months. Start a new discussion instead.