在exe上拖动文件后,ifstream无法打开文件

时间:2011-02-03 11:22:38

标签: c++ parameter-passing ifstream

我遇到以下问题:

ifstream无法打开文件时,我将文件拖放到我的工具(exe) 如果我通过控制台手动给它它可以工作!
我不知道差异在哪里,因为我正在切割路径并仅传递文件名 看看代码:

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();  
      ...  

UPDATE2: 解决方案是:在将文件删除到exe时,“root”文件夹将更改为删除文件来自的文件夹。给硬编码文件提供* .exe的路径解决了它!

1 个答案:

答案 0 :(得分:5)

我猜你当前的目录是错的。不要切断路径。无论如何,你应该做错误检查/调试,看看为什么它无法打开文件。勤勉的调试对于解决问题至关重要,而无需盲目猜测。