Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 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 Reply

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.
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...