我无法确定如何使用close函数关闭文件,因为我在一个单独的函数中打开了一个文件。现在我的程序主要包括3个功能,创建,打开和关闭。创建和打开工作正常,但在我打开文件并返回到我的选项菜单后,我试图能够在没有任何用户输入的情况下关闭文件。我希望close函数检测哪个文件是打开的,然后关闭它。在我打开的时候应该只允许打开一个文本文件(我无法编码,但我假设工作与关闭函数相同)。以下是我的所有代码,还有其他功能我还需要实现,但我现在只担心前三个。谢谢你的帮助!
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
void createDB() {
ofstream db;
string fileName;
cout << "Enter the name of the database you want to create: \n";
getline (cin, fileName);
string fullFile = fileName + ".txt";
std::ifstream fin(fullFile);
if(fin.good()){ // means filename already exists
cout << "\nCould not create database because database name " << fullFile << " is already taken\n";
}
else{ // creates file
cout << "\nYour database " << fullFile << " was created successfully\n";
db.open(fullFile);
}
db.close();
}
void openDB() {
// need to add check to see if one is already open
string fileName;
cout << "Enter the name of the database you want to open: \n";
getline (cin, fileName);
string fullFile = fileName + ".txt";
std::ifstream db(fullFile);
if(db.good()){ // means file exists
cout << "\nThe database " << fullFile << " has been opened successfully\n";
db.open(fullFile);
}
else{ // there is no file named that to open
cout << "\nThere is no database named " << fullFile << " to open\n";
}
}
void closeDB() {
cout << "The database _______ has been closed successfully";
}
void display() {
cout << "Enter the ID of the employee you want to display: \n";
}
void update() {
}
void report() {
}
void add() {
}
void del() {
}
int menu() {
cout << "Enter the number of the operation you wish to perform (1-9)\n"
<< "1. Create new database\n"
<< "2. Open database\n"
<< "3. Close database\n"
<< "4. Display record\n"
<< "5. Update record\n"
<< "6. Create report\n"
<< "7. Add a record\n"
<< "8. Delete a record\n"
<< "9. Quit\n";
int sel = 0;
(std::cin >> sel).ignore();
switch (sel) {
case 1: createDB();
menu(); // after creating file go back to list of options
break;
case 2: openDB();
menu();
break;
case 3: closeDB();
menu();
break;
case 4: display();
break;
case 5: update();
break;
case 6: report();
break;
case 7: add();
break;
case 8: del();
break;
case 9: return 0;
break;
default: cout << "Please try again and enter a valid number\n\n";
menu();
break;
}
return true; // to avoid error saying control may reach end of non-void function
}
int main() {
menu();
return 0;
}
答案 0 :(得分:0)
您必须从打开的文件中接收文件描述符。 c stile: FILE * myfile; myfile = fopen(myfile,“r”); 你可以继续阅读:http://www.cprogramming.com/tutorial/cfileio.html(我认为在c中它更容易理解,它也适用于c ++)。 c ++ stile http://www.cprogramming.com/tutorial/lesson10.html 他解释得非常好。
但你应该记住: 1)你必须创建一个指针(这是他唯一的数据不会丢失的方式)。 2)您必须发送/接收描述符