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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top