【发布时间】:2011-02-03 11:22:37
【问题描述】:
我有以下问题:
当我将文件拖放到我的工具 (exe) 时,ifstream 无法打开文件。
如果我通过控制台手动提供它,它可以工作!
我不知道差异在哪里,因为我正在切断路径并仅传递文件名。
看看代码:
int main(int argc, char* argv[]) {
if (argc < 2) {
cout
<< "ERROR: Wrong amount of arguments! Give at least one argument ...\n"
<< endl;
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
exit(1);
return 0;
}
vector<string> files;
for (int g = 1; g < argc; g++) {
string s = argv[g];
cout<<"parameter at: " << g << " = " << argv[g] << "\n" << endl;
string filename = "";
int pos = s.find_last_of("\\", s.size());
if (pos != -1) {
filename.append(s.substr(pos + 1));
// cout<<" cutted path: " << s.substr(0,s.size()-filename.size()) << endl;
// cout << "argv[1] " << argv[1] << endl;
cout << "\n filename: " << filename << "\t pos: " << pos << endl;
files.push_back(filename);
}
files.push_back(s);
}
for (unsigned int k = 0; k < files.size(); k++)
{
cout << "files.at( " << k << " ): " << files.at(k).c_str() << endl;
Converter a(files.at(k).c_str());
a.getCommandsFromCSV();
a.saveConvertedFile();
}
cout << "\n" << "Programm finished...\n\n" << endl;
cin.ignore();
return 0;
}
它已经在构造函数上失败了:
Converter::Converter(const char* file) {
filename = file;
myfile.open(filename.c_str(), ios_base::in);
cout << (myfile ? "open successful on constructor " : "some error on constructor");
cin.ignore();
trace_raw = "";
}
你知道为什么吗?
更新:
作为参数的文件现在可以工作了。解决方案是保留完整路径。
无论如何,我对硬编码文件有同样的错误。我认为这可能是相同的,这就是为什么我在文件名的开头添加了.\...没有成功。
代码:
void GenericCommandConverter::getATCommandsFromCSV() {
cout << "\t| +++++++++++getATCommandsFromCSV() started+++++++++++++ |"
<< endl;
/*
* CSV file name is hardcoded
*/
string filename_csv = ".\\test.csv";
string commands = "";
int pos_start = 0;
int pos_end = 0; // "|"
int substrLength = 0;
int separator_count = 0;
char c;
vector<string> lines;
vector<string> commandList;
vector<vector<string> > linesSeparated;
ifstream csvFile;
csvFile.open(filename_csv.c_str(), ios_base::in);
cout << (myfile ? "open successful on getATCommandsFromCSV " : "some error on getATCommandsFromCSV ");
cin.ignore();
...
更新 2: 解决方案是:在将文件拖放到 exe 时,“根”文件夹会更改为所拖放文件的来源。为硬编码文件提供 *.exe 的路径解决了它!
【问题讨论】:
-
猜猜:shell 可能还对文件有锁?您可以尝试在打开文件之前添加延迟(不是一个好的解决方案!虽然延迟 + 重试几次可能没问题)或仅打开指定读取锁定的文件 - 不知道如何通过 ifstream 执行此操作。
-
你可以打印
file的值,看看这两种情况下的值是否相同 -
@Kiril Kirov 做了,文件名正确
标签: c++ parameter-passing ifstream