Conducting ios::out & ios::in will lead to something wrong.
When I declared a variable of fstream
and opened a file within my work directory with ios::in | ios::out
, something wrong occured.
- Just only one sort of operation (I/O) can be done normally, and another one can not be done in a normal way.
- The operation that can be done successfully depends on the calling order of reading / writing. If reading is run before writing, the reading will be successful, but the writing will be wrong.
When I separately declare ifstream
and ofstream
variables, the issue was solved.
Here is the source code leading to something wrong:
<code>#include<fstream>
#include<iostream>
using namespace std;
int test_001();
int test_002();
int main() {
// test_001();
// test_002();
}
int test_001() {
std::fstream fs;
// 首先, 如果test.txt不存在, 这串代码并不会创建test.txt
// 其次, 如果test.txt存在, 只能正常执行读/写操作中最先出现的那种操作(如果先读, 就不能写, 如果先写, 后面就不能读).
fs.open("test.txt", std::ios::in|std::ios::out);
fs << "阿米诺斯" << std::endl;
char* s = new char[1024];
fs >> s;
std::cout << s << std::endl;
}
int test_002() {
std::ifstream ifs;
std::ofstream ofs;
// 首先, 如果test.txt不存在, 这串代码会创建test.txt
// 其次, 如果test.txt存在, 读/写能正常执行.
ifs.open("test.txt", std::ios::in);
ofs.open("test.txt", std::ios::out);
ofs << "阿米诺斯" << std::endl;
char* s = new char[1024];
ifs >> s;
std::cout << s << std::endl;
}
</code>
<code>#include<fstream>
#include<iostream>
using namespace std;
int test_001();
int test_002();
int main() {
// test_001();
// test_002();
}
int test_001() {
std::fstream fs;
// 首先, 如果test.txt不存在, 这串代码并不会创建test.txt
// 其次, 如果test.txt存在, 只能正常执行读/写操作中最先出现的那种操作(如果先读, 就不能写, 如果先写, 后面就不能读).
fs.open("test.txt", std::ios::in|std::ios::out);
fs << "阿米诺斯" << std::endl;
char* s = new char[1024];
fs >> s;
std::cout << s << std::endl;
}
int test_002() {
std::ifstream ifs;
std::ofstream ofs;
// 首先, 如果test.txt不存在, 这串代码会创建test.txt
// 其次, 如果test.txt存在, 读/写能正常执行.
ifs.open("test.txt", std::ios::in);
ofs.open("test.txt", std::ios::out);
ofs << "阿米诺斯" << std::endl;
char* s = new char[1024];
ifs >> s;
std::cout << s << std::endl;
}
</code>
#include<fstream>
#include<iostream>
using namespace std;
int test_001();
int test_002();
int main() {
// test_001();
// test_002();
}
int test_001() {
std::fstream fs;
// 首先, 如果test.txt不存在, 这串代码并不会创建test.txt
// 其次, 如果test.txt存在, 只能正常执行读/写操作中最先出现的那种操作(如果先读, 就不能写, 如果先写, 后面就不能读).
fs.open("test.txt", std::ios::in|std::ios::out);
fs << "阿米诺斯" << std::endl;
char* s = new char[1024];
fs >> s;
std::cout << s << std::endl;
}
int test_002() {
std::ifstream ifs;
std::ofstream ofs;
// 首先, 如果test.txt不存在, 这串代码会创建test.txt
// 其次, 如果test.txt存在, 读/写能正常执行.
ifs.open("test.txt", std::ios::in);
ofs.open("test.txt", std::ios::out);
ofs << "阿米诺斯" << std::endl;
char* s = new char[1024];
ifs >> s;
std::cout << s << std::endl;
}
New contributor
Noah Miller is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5