使用C ++代码检查txt文件是否存在

问题描述:

首先,我要确定我的文件夹目录中确实有文本文件.我正在使用Visual Studio,这是我的源代码编译的地方.

First of all, i'd to establish that i do have the text file in my Folders directory. Im using visual studio and it is where my source code is compiling.

下面的代码应说明其不起作用的原因.在Visual Studio中.

The code below should demonstate why its not working. In visual studio.

int main( const int argc, const char **argv )
{
    char usrMenuOption;
    const char *cFileName = argv[ 1 ];
    checkName( cFileName );  // supplying the checkName function with contents of argv[1]

    usrMenuOption = getUsrOption();  // calling another function

    fgetc(stdin);
         return 0;
}
ifstream *openInputFile( const char *cFileName )
{
    // this function might be the pronblem.
    ifstream *inFile;
    inFile = new ifstream; 
    inFile->open( cFileName, ios::in );
    return inFile;
}
bool checkName( const char *cFileName )
{
    // it works fine if i use a regular ifstream obj and not the one from the function
    ifstream *inFile;
    inFile = openInputFile( cFileName );
    inFile->open( cFileName, ios::in );

    if ( inFile->good() )
    { 
        return true;
    }
    else
    { 
        cout << '"' << cFileName << '"' << ": File does not exist! " << endl;
        return false;
    }         
}

如果我为ifstream使用非指针对象,它确实可以工作. 但是,我需要使用我创建的功能以这种方式打开所有输入文件. 我有点困惑,因为我没有在dev-cpp中编译此问题

It does work if i use a non-pointer object for the ifstream. however i need to open all of my input files this way, using the function i made. I'm a little confused because i did not have this issue compiling in dev-cpp

我总是检查ifs.is_open(),其中ifs是ifstream.

I always check ifs.is_open() where ifs is a ifstream.