C++ 新手求 关于文件操作的帮助
我想写一个程序生成一个exe,就叫a.exe吧,在cmd下 输入 a.exe 0.txt 实现将0.txt中的内容显示出来,运行如下代码,总显示代码里的open file error,意思是文件没打开。 小弟菜鸟一枚,求高手指点!
#include"stdafx.h"
#include<fstream>
#include<string>
#include<iostream>
using namespace std;
int main(int argc,char *argv[])
{
string str;
fstream file;
file.open(argv[1]);
if (file.is_open())
{
while(!file.eof())
{
getline(file,str);
cout<<str;
}
}
else cout<<"open file error!"<<endl;
return 0;
}
[解决办法]
代码没有问题,注意目录!
进入CMD后,把当前目录设置到你a.exe所在的目录下,并把0.txt也放在该目录下,就可以执行了。
[解决办法]
检查0.txt这个文本文件是否和a.exe在同一个目录中。
[解决办法]
代码没问题,可能输入的参数有问题
#include"stdafx.h"#include<fstream>#include<string>#include<iostream>using namespace std;int main(int argc,char *argv[]){ cout<<argv[1]<<endl; string str; fstream file; file.open(argv[1]); if (file.is_open()) { while(!file.eof()) { getline(file,str); cout<<str; } } else cout<<"open file error!"<<endl; return 0;}
[解决办法]
调试一下,查找问题所在