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;
}
}

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

Bo Persson

DaVinci said:
//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;
}
}

what's the problem is ?
thanks very much.

In what directory do you expect the file a.txt to be found? How does
the program know that?


Bo Persson
 
J

Jacek Dziedzic

DaVinci said:
//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;
}
}

what's the problem is ?

Are you sure you have the permissions to open this file
for read/write? IOW, the existence of the file does not
automatically imply you will manage to open it successfully.

HTH,
- J.
 

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