c ++ linux ifstream读取csv文件 [英] c++ linux ifstream read csv file

查看:652
本文介绍了c ++ linux ifstream读取csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]没有读...为什么?

This function reads a 2-column csv file and creates a map of column2 with column1 as the key. I compiled with g++ and the file is on the university file share, when I run the program with ./foo the csv files [in the same directory folder as foo] are not read... why?

推荐答案

也许你没有该文件的读取权限。发出命令 ls -l< csv_file>
查看您是否有权限读取。有关文件权限的详细信息,请参阅此链接 https://help.ubuntu.com/community/FilePermissions

Perhaps you don't have read permission from that file. Issue the command ls -l <csv_file> see if you have right to read from. For more information on file permissions refer to this link 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读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆