Hi. I'm using ifstream and ofstream operations in DEV c++ but they don't seem to work correctly. I've been trying to write a little prime generator code but it doesn't work :\ When I display fstream::tellg() at any point, it displays -1. Please check the code. Thanx.
#include<iostream>
#include<math.h>
#include<fstream>
using namespace std;
int prime (unsigned long long n)
{
ifstream f1;
ofstream f2;
unsigned long long i,m,root;
int flag=0;
for(i=2;i<=n;i++)
{
f1.open("prime2.txt",ios::binary);
if(!f1.is_open())
{
cout<<"NOT OPEN";
}
cout<<f1.tellg()<<" "; //Displaying getpointer pos
flag=0;
root=(unsigned long long)sqrt(i);
while(f1.read((char*)&m,sizeof(m)))
{
if((i%m)==0)
{
flag=1;
break;
}
if(m>root)
{
break;
}
}
f1.close();
if(!flag)
{
f2.open("prime2.txt",ios::app|ios::binary);
f2.write((char*)&i,sizeof(i));
cout<<i<<" "; //Displaying num being written
f2.close();
}
}
return 1;
}
int main(int argc, char* argv[])
{
prime(50);
system("pause");
}
(I'm sorry, i just couldn't make the whole thing get in one codeblock. I guess theres something wrong with [code] tag?)
Output:
NOT OPEN-1 2 -1 3 -1 4 -1 5 -1 6 -1 7 -1 8 -1 9 -1 10 -1 11 -1 12 -1 13 -1 14 -1
15 -1 16 -1 17 -1 18 -1 19 -1 20 -1 21 -1 22 -1 23 -1 24 -1 25 -1 26 -1 27 -1 2
8 -1 29 -1 30 -1 31 -1 32 -1 33 -1 34 -1 35 -1 36 -1 37 -1 38 -1 39 -1 40 -1 41
-1 42 -1 43 -1 44 -1 45 -1 46 -1 47 -1 48 -1 49 -1 50 Press any key to continue
. . .
PS: I'm relatively new to programming, and only just started on DEV cpp a couple of days ago. Before that i used Turbo C...and a (similar) code worked well on it.