使用C ++代码检查txt文件是否存在 [英] Checking existence of a txt file with C++ code

查看:87
本文介绍了使用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.

这篇关于使用C ++代码检查txt文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆