Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

my c++ file is not opened , why?

 cout<<"enter name of file : " <<endl;
    char nof[30] ;
    for (int i=0;i<20;++i){
            cin>>nof[i];
        if (nof[i-1]=='x'){
            if (nof[i]=='t'){
               break;
            }
        }
    }
    fstream file1;
    file1.open(nof);
    if (file1.is_open()) cout<<"file is open"<<endl;

that is a code which should take the name of file from user to create but i checked if it is opened and it is not , what to do ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using this:

#include <string>
#include <iostream>
#include <errno.h>
#include <fstream>
#include <cstring>

using namespace std;

int main() {
    cout << "Enter the name of the file : ";
    string file_name;
    getline(cin, file_name);

    fstream file_stream;
    file_stream.open(file_name);

    if (file_stream.is_open()) {
        // File Stuffs goes here...........
        cout << "The file is open" << endl;
    } else {
        // The file may not exists or locked by some other process.
        cout << strerror(errno) << endl; // Edited this line.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...