Hi
I want to write a program that opens a file and counts the number of characters in the file. If any one has a solution I would appreciate it.
Thanks in advance for your help.
Printable View
Hi
I want to write a program that opens a file and counts the number of characters in the file. If any one has a solution I would appreciate it.
Thanks in advance for your help.
Code:#include <iostream>
#include <fstream>
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();
std::cout << "number of characters (method 1) = " << length << std::endl;
/////////
in.seekg(0,std::ios::beg);
int count = 0;
char c;
while(in.get(c))
++count;
std::cout << "number of characters (method 2) = " << count << std::endl;
return 0;
}
Thanks for your reply
I tried your program and it compiled but it wouldn't work - got the result of 0 characters when my .dat file contained around 20 characters.
Any ideas?
Thanks in advance for your help.
I tested on 4 different compilers, and it worked fine.
Are you using the standard headers <fstream> , or
the old non-standard headers <fstream.h>
Under Windows, I think that if you use the non-standard
headers, and the file does not exists, the error check
in the code doesn't work. (just to be sure: did you
change the name in the file open ? and is it in
the correct folder, etc.)
After my post, I editted it and added a second method.
Did you try that ?
Hi
I am using Windows XP and using Visual C++ 6
I have edited one bit of your code which is the file name. This is the code:
#include <iostream>
#include <fstream>
int main()
{
std::ifstream in("c:hello.dat",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();
std::cout << "number of characters (method 1) = " << length << std::endl;
/////////
in.seekg(0,std::ios::beg);
int count = 0;
char c;
while(in.get(c))
++count;
std::cout << "number of characters (method 2) = " << count << std::endl;
return 0;
}
I still get the problem that I get 0 returned when there are 20 characters in my dat file.
Any ideas?
Thanks in advance for your help
that code should work.
Just for the sake of it, try this piece of C code
PHP Code:#include <stdio.h>
int main()
{
FILE *myfile;
unsigned long sizeofmyfile;
myfile = fopen("myfile.dat","rb");
if(myfile==NULL)
{
printf("could not open file\n");
return -1;
}
fseek(myfile,0,SEEK_END);
sizeofmyfile=ftell(myfile);
printf("My file has a size of %ld bytes\n",sizeofmyfile);
return 0;
}
If 3 methods fail, then i'm pretty sure that you are doing something else wrong.