2013-01-11 150 views
0
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文件,并创建一个column1映射,并以column1作为键。我使用g ++进行编译,并且该文件位于大学文件共享中,当我使用./foo运行程序时,csv文件[与foo在同一目录文件夹中]不会被读取......为什么?C++ linux ifstream读取csv文件

+1

你得到什么消息,当您尝试运行? – hmatar

+0

#Hassan TM该程序运行正常,但从cout检查我可以看到该文件没有被读取 –

回答

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(); 
} 
+0

#Hassan TM该命令返回“缺少重定向名称”。 –

+0

我在编译你的代码。 ...等待 – hmatar

+0

在g ++和VS2008中编译,但仍然有一些地图 - 我会尝试一些更多的测试,并尝试更好地确定问题的范围 –