C++ questions
UPDATE Is it possible to print out all the data that f.open has gained before using f.close() to completely close the file and finalize the File Writing???
ex.
int main()
{
ofstream f ("test.txt", ios::app);
string data = "Stuff to store in text document.";
int i=10;
while (i>0)
{
f << data << "\n";
i--;
}
cout << f;
f.close();
return 0;
}
COM wrote: [quote]Froger wrote: I figured f.close() would mark the beginning of the text document update It… does. But I guess it's hard to notice in your program since it quits right after it closes it.[/quote]
Then may I ask this, why in the example below, does it not update?
int main()
{
int i=10;
while (i>0)
{
string text;
ofstream f ("test.txt", ios::out);
getline(cin, text);
f << text << "\n";
f.close();
}
return 0;
}
Also COM, thanks for the reply. It is much appreciated. I have viewed like 20 different tutorials on file writing and just couldn't exactly find what I was looking for. I guess I really don't know how to look for what I am looking for on google.
Froger wrote: Then may I ask this, why in the example below, does it not update?
int main()
{
int i=10;
while (i>0)
{
string text;
ofstream f ("test.txt", ios::out);
getline(cin, text);
f << text << "\n";
f.close();
}
return 0;
}
Well you might want to try to use ios::app so it doesn't wipe the text file clean every time it reopens. ios::out is pretty redundant since you're opening an ofstream anyhow.
starofale wrote: [quote]Froger wrote: Bumping thread, look at original post. It would have been better to just put the new information in a new post and leave the original. That way other people can understand what was going on and it might have helped people who have the same problem.[/quote]
I will take that into consideration next time. Sorry if I caused you any problems/frustrations.
Froger wrote: Is it possible to print out all the data that f.open has gained before using f.close() to completely close the file and finalize the File Writing??? As starofale said, changing the initial post was pretty stupid. Anyhow, good question, I've never actually tried that… Looked around a bit quickly and you could do something akin to this:
{
string fuckyou;
fstream ohnoes("ohnoes.txt", ios::in|ios::out|ios::trunc);
if(!ohnoes.good())
{
cout<<"wtfx"<<endl;
return 1;
}
do
{
getline(cin, fuckyou);
ohnoes<<fuckyou;
}while(!fuckyou.empty());
ohnoes.seekp(0, ios_base::beg);
char *outp=new char[ohnoes.rdbuf()->in_avail()+1];
outp[ohnoes.rdbuf()->in_avail()]=0;
ohnoes.read(outp, ohnoes.rdbuf()->in_avail());
cout<<outp<<endl;
delete[] outp;
ohnoes.close();
return 0;
}```
Apparently the ofstream class isn't meant to, you know... be read from.