wrong about fstream file(s.c_str(),std::ios_base::in | std::ios_base::app);

D

DaVinci

//error happen even when there existe a a.txt file
#include<fstream>
#include <string>
#include <iostream>
using std::string;
using std::fstream;
int main()
{
string s = "a.txt";
fstream file(s.c_str(),std::ios_base::in | std::ios_base::app);
if(!file)
{
std::cerr<<"error happen\n";
}
else
{
string readToStr;
file>>readToStr;
file<<"abc";
std::cout<<"successed"<<std::endl;
}
}

the output is alway "error happen" even when There exist a file named
a.txt.

what's the problem is ?
thanks very much.
 
S

Sergiy Kanilo

fstream file(s.c_str(),std::ios_base::in | std::ios_base::app);

Combination std::ios_base::in | std::ios_base::app is not valid
for opening the file and causes the failure.

Cheers,
Serge
 
F

Fraser Ross

"Sergiy Kanilo"
Combination std::ios_base::in | std::ios_base::app is not valid
for opening the file and causes the failure.

I think it is. out is implied by app.

What compiler and STL implementation is being used?

Fraser.


*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from http://www.SecureIX.com ***
 
B

BobR

Fraser Ross wrote in message
"Sergiy Kanilo"

I think it is. out is implied by app.

What compiler and STL implementation is being used?
Fraser.

DejaVu all over again! <G>

using std::cout;
std::string s = "za.txt";
{ std::eek:fstream Tfile(s.c_str()); Tfile<<s<<std::endl; }
{
std::fstream file(s.c_str(), std::ios_base::in | std::ios_base::app);
if(!file){ cout<<"1-error happen\n"; }
else{ // snipped content here
cout<<"1-successed"<<std::endl;
}
}
{
std::fstream file(s.c_str(), std::ios_base::in);
if(!file){ cout<<"2-error happen\n"; }
else{
std::string readToStr;
file>>readToStr; // snipped file write
cout<<"2-successed"<<std::endl;
}
}
{
std::fstream file(s.c_str(), std::ios_base::eek:ut | std::ios_base::app);
if(!file){ cout<<"3-error happen\n"; }
else{
file<<"3-abc";
cout<<"3-successed"<<std::endl;
}
}
// --- output ---
// 1-error happen
// 2-successed // file contents: za.txt
// 3-successed // file contents: za.txt'\n' 3-abc

GCC g++ 3.3.1 MinGW
 
D

DaVinci

Sergiy said:
Combination std::ios_base::in | std::ios_base::app is not valid
for opening the file and causes the failure.
why?
fstream file(s.c_str(),std::ios_base::in | std::ios_base::eek:ut) is ok.
the std::ios_base::eek:ut and std::ios_base::app are both used to write
to a file.
The difference is just one will overwrite and the other will append.
I think there is no much difference between them,why one can the other
can't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top