c ++ linux ifstream读取csv文件

时间:2013-01-11 17:43:45

标签: c++ linux g++ ifstream

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文件并创建column2的映射,其中column1为键。我用g ++编译并且文件在大学文件共享上,当我用./foo运行程序时,csv文件[与foo在同一个目录文件夹中]不读...为什么?

1 个答案:

答案 0 :(得分:2)

也许您没有该文件的读取权限。发出命令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();
}