c++ - 在Windows上打开的C++文件始终失败

标签 c++ file ifstream

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

cpp file open fails

所以我对正在发生的事情不知所措,因为我看过的所有其他示例看起来都应该起作用。
例如:
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”那样对它们进行转义。

关于c++ - 在Windows上打开的C++文件始终失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62009270/

相关文章:

c++ - 从文件中的一行获取特定部分(C++)

c++ - 有没有办法为 NUMA 中的数据分配特定的内存?

c++ - 从日志格式中解耦异常

c++ - main() 会捕获线程抛出的异常吗?

java - 从程序文件获取文件

java - 如何在目录中搜索以String开头的文件

c++ - ifstream,行尾并移至下一行?

c++ - 外部库处理多边形并计算它们的分形维数

具有不完整列的 Linux 文件排序

c++ - 从文本文件打开和编辑数值数据并将结果放入新文件,C++