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

fstream error cannot create or open file in c++

本文关键字:创建 文件 错误 fstream      更新时间:2023-10-16

每当要输入选项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`*

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

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

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

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