fstream错误无法在c ++中创建或打开文件

时间:2017-10-05 11:49:16

标签: c++ fstream

每当ty输入选项1来创建一个文件来存储我的数据 生成错误。我无法创建文件而无法阅读

*//cannot create the file*
#include <fstream> 
class file
{   
private:                       
    char data[100];
public:
    void Write();
    void Read();
};
*//this is the write function*     help me
void file::Write() {
    *//fin object is created*
    fstream fin;
    *//cant open the file*
    fin.open("rahul.txt", ios::in);
    if (fin.is_open()) {                             help me
        cout << "Enter data" << endl;
        cin.ignore();
        cin.getline(data, 100);
        fin.close();
    } else
        cout << "error" << endl;          help me
}
*//this is the read function*

void file::Read() {
    *//fout object is created*
    fstream fout;
    *//cant read the file*                   help me
    fout.open("rahul.txt", ios::out);
    if (fout.is_open()) {
        while (!fout.eof()) {
            fout.getline(data, 100);
            cout << data;                     help me
        }
        fout.close();
    } else
        cout << "error" << endl;
}

int main() {
    int choice;
    file f;
    while (1) {
        cout << "Menu" << endl;
        *//cant enter the file when pressed choice 1*
        cout << "1.Enter  2.Display   3.exit" << endl;
        cout << "Enter your choice" << endl;
        cin>>choice;
        switch (choice) {
            case 1:
                f.Write();
                break;
            case 2:
                f.Read();
                break;                   help me
            case 3:
                return 0;
        }
    }
    return 0;
}
*`//cant enter the file`*

请有人帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

fin.open("rahul.txt", ios::in);中使用的开放模式要求该文件已存在。并且放在“当前目录”中,无论是什么,因为您没有指定路径。

模式in也只允许您从文件中读取。

fout.open("rahul.txt", ios::out);中使用的打开模式将创建一个用于写入的空文件(替换任何以前具有相同名称的文件)。由于两个原因,尝试从该文件读取将失败 - 该文件始终为空,并且只能写入。