可以使用C++可以打开文件
我正在使用Linux G ++编译器和Visual Studio代码来编译和运行下面的代码,并且每次运行时,它都会用Cable Open File返回。我已经将文本文件放在与C ++程序相同的文件夹中,但仍然无济于事。 谁能指出我出错的地方?
代码:
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 1) {
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if (ifile.fail()) {
cerr << "Could not open file." << endl;
return 1;
}
return 0;
}
I am using linux g++ compiler and also visual studio code to compile and run the code below and each time I run it, it returns with could't open file. i have put the text file in the same folder as the c++ program but still to no avail.
Can anyone point out where I have gone wrong?
The code:
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
if (argc < 1) {
cerr << "Usage: " << argv[0] << "filename.txt" << endl;
}
ifstream ifile(argv[1]);
if (ifile.fail()) {
cerr << "Could not open file." << endl;
return 1;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您已将文件名给了该程序作为一个
参数。
由G ++编译后,您应该这样运行以下程序:
argv [1]
是第一个程序参数,在这种情况下“ filename.txt”。
确保在同一工作目录中启动该程序的任何内容
请确保文件程序具有足够的权限可以读取文件。可以通过
chmod
。更改。
Make sure that you have given the filename to the program as an
argument.
After being compiled by g++, you should run the program like this:
argv[1]
is the first program argument, in this case"filename.txt".
Make sure that whatever launches the program is in the same working directory
Make sure that the file program has sufficient permissions to read the file. This can be changed with
chmod
.