-
Help with file Streams
I need to make this program write to a file and read it. I have got the writing part down but when it tries to read and display the information i get wierd numbers can anyone tell me whats wrong?
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
int main()
{
int num;
int counter=0;
int enter;
ofstream outstream("digits2.dat");
if(outstream.fail())
{
cout<<"File Problem"<<endl;
exit(1);
}
for(counter=0; counter<5; counter++)
{
outstream<<1;
outstream<<2;
outstream<<3;
}
outstream.close();
ifstream instream("digits2.dat"); //opens files for reading
if (instream.fail() )
{
cout<<"File problem!"<<endl;
exit(1); //stop execution
}
while (instream>>num)
{
for(counter=0; counter<5; counter++)
{
cout<<num;
}
counter++;
outstream<<num;
cout<<num<<" ";
}
cout<<num<<endl;
cout<<"There were "<<counter<<" numbers read"<<endl;
instream.close();
cout<<"\n\n Program finished";
cin>>enter;
return(0);
}
-
ell to find a string within a line read from a file, do something like this...
#include <stdio.h>
#include <string.h>
int main ( ) {
char buff[BUFSIZ];
FILE *fp = fopen("keywords.txt","r");
while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
if ( strstr(buff,"word") != NULL ) {
printf( "%s", buff );
}
}
fclose( fp );
return 0;
}
-
have you opened digits2.dat to see what's in it? Maybe you have a problem writing to the file, not reading from it.
You may need to make a call to clear() after the call to fail(). I generally use the syntax: if(!outstream)
After the first half of your program you close the ofstream. But then you use it again in the second half of the program without reopening it.
outstream << 2; might not put anything in the file. to print 2 to the file try this outstream << "2"; or outstream << '2';