use*_*120 3 c++ file visual-studio
首先,我要确定我的文件夹目录中有文本文件.我使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我为ifstream使用非指针对象,它确实有效.但是我需要使用我所做的功能以这种方式打开我的所有输入文件.我有点困惑,因为我没有在dev-cpp编译这个问题
OJ.*_*OJ. 13
你有几个选择:
保证它存在并且可以使用它的唯一方法是打开它.如果您使用其他方法,最终会出现竞争条件(因为在您检查文件是否存在后,该文件可能会被删除或锁定.
编辑:您的代码中还有其他几个问题.首先,你分配一个infile通道new,但你永远不会delete.其次,你打open两次电话.