Linux编程ifstream的读取csv文件(c++ linux ifstream read cs

2019-11-01 09:16发布

void Lexicon::buildMapFromFile(string filename )  //map
{
    ifstream file;
    file.open(filename.c_str() );
    string wow, mem, key;
    unsigned int x = 0;

    while(true) {
        getline(file, wow);
        if (file.fail()) break; //check for error
        while (x < wow.length() ) {
            if (wow[x] == ',') {
                key = mem;
                mem.clear();
                x++; //step over ','
            } else 
                mem += wow[x++];
        }

        list_map0.put(key, mem); //char to string
        list_map1.put(mem, key); //string to char
        mem.clear(); //reset memory
        x = 0;//reset index
    }
    file.close();
}

该函数读取一个2列csv文件并创建地图列2的列1与作为密钥。 我用G ++编译和文件是对大学的文件共享,当我运行./foo的CSV文件[如中富同一个目录文件夹]不看节目......为什么?

Answer 1:

也许你没有从文件中读取的权限。 发出命令ls -l <csv_file>看看你有没有正确的阅读。 有关文件权限的详细信息请参考以下链接https://help.ubuntu.com/community/FilePermissions

试试下面的代码工作非常适合我

   #include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#include <fstream>
using namespace std;


int main(void )  //map
{
   map<string, string> list_map0;

   map<string, string> list_map1;
    string filename = "csv";
    ifstream file;
    file.open(filename.c_str() );
    string wow, mem, key;
    unsigned int x = 0;

    while(true) {
        getline(file, wow);
        if (file.fail()) break; //check for error
        while (x < wow.length() ) {
            if (wow[x] == ',') {
                key = mem;
                mem.clear();
                x++; //step over ','
            } else
                mem += wow[x++];
        }

        list_map0[key] = mem; //char to string
        list_map1[mem] = key; //string to char
        mem.clear(); //reset memory
        x = 0;//reset index
    }
    printf("%d\n", list_map0.size());
    file.close();
}


文章来源: c++ linux ifstream read csv file