I'm attempting to create a program that uses fstream objects to read/write to files. However, it is currently balky at best. The fstream.write call doesn't return an error, but the modified data doesn't show in the next read, or when I open the file itself. Additionally, I get a insufficient parameters error from if I remove the ios flags from the open--from what I have read, isn't fstream supposed to default the flags to ios::in|ios::ou t? I am using BC5 to compile, if that makes a difference.
My code is currently as follows:
#include <fstream.h>
#include <conio.h>
void fileRead(fstrea m &testFile,ch ar testTxt[]);
void fileWrite(fstre am &testFile,ch ar newTxt[]);
void main()
{
char testTxt[11]="\0\0\0\0\0\0\ 0\0\0\0\0";
char newTxt[6]="zxcvb\0";
fstream testFile;
testFile.open(" dataFile.txt",f stream::in | fstream::out | fstream::binary );
fileRead(testFi le,testTxt);
cout <<"\n\n1. Overwrite"<<end l;
cout <<"\n2. Re-Read"<<endl;
int i=0;
while (i!=27)
{
while (!kbhit())
;
i=getch();
switch(i)
{
case 49:
fileWrite(testF ile,newTxt);
case 50:
fileRead(testFi le,testTxt);
break;
case 27:
break;
default:
cout <<"Press one or two."<<endl;
}
}
}
void fileRead(fstrea m &testFile,ch ar testTxt[])
{
testFile.seekg( 0,ios::beg);
testFile.read(t estTxt,10);
if (!testFile.bad( ))
cout <<"dataFile txt: "<<testTxt<<end l;
else
cout <<"Error!"<<end l;
testFile.sync() ;
return;
}
void fileWrite(fstre am &testFile,ch ar newTxt[])
{
testFile.seekp( 0,ios::beg);
testFile.write( newTxt,5);
if (!testFile.bad( ))
cout <<"Text overwritten!"<< endl;
else
cout <<"Error!"<<end l;
testFile.sync() ;
return;
}
dataFile.txt contains the string
"asdfghjkl"
My code is currently as follows:
#include <fstream.h>
#include <conio.h>
void fileRead(fstrea m &testFile,ch ar testTxt[]);
void fileWrite(fstre am &testFile,ch ar newTxt[]);
void main()
{
char testTxt[11]="\0\0\0\0\0\0\ 0\0\0\0\0";
char newTxt[6]="zxcvb\0";
fstream testFile;
testFile.open(" dataFile.txt",f stream::in | fstream::out | fstream::binary );
fileRead(testFi le,testTxt);
cout <<"\n\n1. Overwrite"<<end l;
cout <<"\n2. Re-Read"<<endl;
int i=0;
while (i!=27)
{
while (!kbhit())
;
i=getch();
switch(i)
{
case 49:
fileWrite(testF ile,newTxt);
case 50:
fileRead(testFi le,testTxt);
break;
case 27:
break;
default:
cout <<"Press one or two."<<endl;
}
}
}
void fileRead(fstrea m &testFile,ch ar testTxt[])
{
testFile.seekg( 0,ios::beg);
testFile.read(t estTxt,10);
if (!testFile.bad( ))
cout <<"dataFile txt: "<<testTxt<<end l;
else
cout <<"Error!"<<end l;
testFile.sync() ;
return;
}
void fileWrite(fstre am &testFile,ch ar newTxt[])
{
testFile.seekp( 0,ios::beg);
testFile.write( newTxt,5);
if (!testFile.bad( ))
cout <<"Text overwritten!"<< endl;
else
cout <<"Error!"<<end l;
testFile.sync() ;
return;
}
dataFile.txt contains the string
"asdfghjkl"
Comment