2013-01-11 148 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中編譯,但仍然有一些地圖 - 我會嘗試一些更多的測試,並嘗試更好地確定問題的範圍 –