void kick_start() {
//function must run at start to create files
fstream passkey;fstream database;
//so that when password is changed its always overwritten
passkey.open("key.txt", ios::out | ios::in);
if (!passkey) {
cout << "!!!ERROR OPENING CRITICAL SYSTEM FILES!!!\b" << endl;
cout << "PROGRAM WILL NOW EXIT" << endl;
Sleep(1500);
exit(1);
}
database.open("Mainbase.txt", ios::app | ios::in);
if (!database) {
cout << "!!!ERROR OPENING CRITICAL SYSTEM FILES!!!\b" << endl;
cout << "PROGRAM WILL NOW EXIT" << endl;
Sleep(1500);
exit(1);
}
int temp;
temp = passkey.tellg();
cout << temp;
}
int main() {
//main function for the whole project
start_animation anime;
anime.animation();
kick_start();
_getch();
return 0;
}
一切看起来都不错,但程序总是退出,代码1无法理解为什么每次调用函数kick_start()它都会退出程序。
答案 0 :(得分:1)
好的,我通过一个简单的测试程序找出了你的问题:
#include <iostream>
#include <fstream>
int main()
{
{
std::cout << "text2.txt: std::ios_base::in | std::ios_base::out" << std::endl;
std::fstream foo("text2.txt", std::ios_base::in | std::ios_base::out);
std::cout << std::boolalpha << bool(foo) << std::endl;
}
{
std::cout << "text3.txt: std::ios_base::in | std::ios_base::app" << std::endl;
std::fstream foo("text3.txt", std::ios_base::in | std::ios_base::app);
std::cout << std::boolalpha << bool(foo) << std::endl;
}
{
std::cout << "create text4.txt" << std::endl;
std::fstream foo("text4.txt", std::ios_base::out);
}
{
std::cout << "text4.txt: std::ios_base::in | std::ios_base::out" << std::endl;
std::fstream foo("text4.txt", std::ios_base::in | std::ios_base::out);
std::cout << std::boolalpha << bool(foo) << std::endl;
}
{
std::cout << "text4.txt: std::ios_base::in | std::ios_base::app" << std::endl;
std::fstream foo("text4.txt", std::ios_base::in | std::ios_base::app);
std::cout << std::boolalpha << bool(foo) << std::endl;
}
return 0;
}
有了这个,我得到以下输出:
text2.txt: std::ios_base::in | std::ios_base::out
false
text3.txt: std::ios_base::in | std::ios_base::app
true
create text4.txt
text4.txt: std::ios_base::in | std::ios_base::out
true
text4.txt: std::ios_base::in | std::ios_base::app
true
在我的exe目录中,我创建了2个文件(不是3个):text3.txt和text4.txt。 this page上的表格解释了此行为。
modestring openmode & ~ate Action if file already exists Action if file does not exist
"a" app, out|app Append to file Create new
"r+" out|in Read from start Error
所以基本上它只是一个标志问题,要么预先创建文件,要么在两者上使用相同的标志(因为你在评论中说过“我通过评论密码部分检查它似乎只有passkey失败但数据库成功创建,因为它没有给出错误消息“)。
P.S:找不到文件可能是由我在评论中提到的,即您的路径相对于.exe而工作目录位于其他地方(这是Visual Studio中的默认路径)