在 windows 上打开 C++ 文件总是失败

C++ file open on windows always fails

我从另一个类似问题的答案中得到了这段代码,但我不明白为什么这对我不起作用。 test.csv 与编译后的 .exe 文件位于同一文件夹中,但找不到它。我尝试了完整的系统路径 ("C:\Users\hhv\eclipse-workspace\oncemore\Debug\test.csv") 但它仍然无法打开 csv。

所以我对正在发生的事情一头雾水,因为我看过的所有其他示例看起来都应该有效。 前任: https://github.com/tpatil2/C-Programs/blob/master/RWcsv/rwcsv.cpp

c++ reading csv file



#include <iostream>
#include <fstream>
#include <sstream>

#include <string>
#include <vector>
#include "load_symbol.h"
using namespace std;


bool load_symbols(){


     string line;                    /* string to hold each line */
     vector<vector<int>> array;      /* vector of vector<int> for 2d array */

     ifstream f ("test.csv");   /* open file */
        if (!f.is_open()) {     /* validate file open for reading */
            perror ("error while opening symbol file ");
            return false;
        }

        while (getline (f, line)) {         /* read each line */
            string val;                     /* string to hold value */
            vector<int> row;                /* vector for row of values */
            stringstream s (line);          /* stringstream to parse csv */
            while (getline (s, val, ','))   /* for each value */
                row.push_back (stoi(val));  /* convert to int, add to row */
            array.push_back (row);          /* add row to array */
        }
        f.close();

        cout << "complete array\n\n";
        for (auto& row : array) {           /* iterate over rows */
            for (auto& val : row)           /* iterate over vals */
                cout << val << "  ";        /* output value      */
            cout << "\n";                   /* tidy up with '\n' */
        }


        return true;


}

路径是相对于当前工作目录(程序执行的地方),而不是源文件。此外,当您在文件路径中使用反斜杠时,您必须像这样转义它们 "C:\Users\hhv\eclipse-workspace\oncemore\Debug\test.csv"