[英]C++ Able to open a file in Code::Blocks with its full path, but not with relative path as a command line argument
I am working on a C++ homework project in Code::Blocks where the file name to open is specified in the first command line argument. 我正在Code :: Blocks中的C ++家庭作业项目中,在第一个命令行参数中指定了要打开的文件名。 The file I am trying to open is titled InputFile1.txt.
我尝试打开的文件名为InputFile1.txt。 When I run the code below:
当我运行以下代码时:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <unistd.h>
using std::cout;
using std::ifstream;
using std::ofstream;
using std::cerr;
int main(int argc, char *argv[])
{
ifstream inputFile;
puts(getcwd(0,1234));
inputFile.open(argv[1]);
if (inputFile.is_open())
{
cerr << "Couldn't open file " << argv[1];
return(EXIT_FAILURE);
}
cout << "\nThe file to search is: " << argv[1];
return(EXIT_SUCCESS);
}
The error message "Couldn't open file InputFile1.txt" is displayed. 显示错误消息“无法打开文件InputFile1.txt”。 However when I type in the full path to InputFile1.txt the file successfully opens as indicated by the output of the message on the bottom.
但是,当我输入InputFile1.txt的完整路径时,文件成功打开,如底部消息的输出所示。 The following troubleshooting steps have been taken:
已采取以下故障排除步骤:
My analysis: 我的分析:
Any insights/help would be greatly appreciated. 任何见解/帮助将不胜感激。
It turns out that the code listed above was working correctly. 事实证明,上面列出的代码运行正常。 The if statement in the code below:
以下代码中的if语句:
inputFile.open(argv[1]);
if (inputFile.is_open())
{
cerr << "Couldn't open file " << argv[1];
return(EXIT_FAILURE);
}
was evaluating the result of the expression inputFile.is_open()
, which returned true when the file was successfully opened. 正在评估expression
inputFile.is_open()
的结果,当文件成功打开时返回true。 To check if the file had not been successfully opened, the expression !inputFile.is_open()
should have been used. 要检查文件是否未成功打开,应使用表达式
!inputFile.is_open()
。 Thanks to my prof for helping me resolve this issue - the error was all my own. 感谢我的教授帮助我解决了这个问题-该错误是我自己的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.