【问题标题】:c++ linux ifstream read csv filec++ linux ifstream读取csv文件
【发布时间】:2013-01-11 17:43:45
【问题描述】:
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 作为键的 column2 的映射。我用 g++ 编译,文件在大学文件共享上,当我用 ./foo 运行程序时,csv 文件 [在与 foo 相同的目录文件夹中] 未被读取......为什么?

【问题讨论】:

  • 当您尝试运行时收到什么消息?
  • #Hassan TM 程序运行正常,但从 cout 检查我可以看到文件未被读取

标签: c++ linux g++ ifstream


【解决方案1】:

也许您没有读取该文件的权限。发出命令ls -l &lt;csv_file&gt; 看看你是否有权阅读。有关文件权限的更多信息,请参阅此链接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();
}

【讨论】:

  • 在 g++ 和 VS2008 中编译,但地图仍有问题 - 我将尝试更多测试并尝试更好地解决问题
  • 不要写,就是ls -l filename
  • 感谢标记。在 Linux 社区中,我们使用这些标记来表示变量属性。
  • 这里的软件开发人员认为他找到了问题 - 当我错误地将 ',' 用作其中一个键时,我的代码解析中存在错误,感谢您的帮助
  • 后续 - 在进一步检查 unicode 之后,看起来相等但是不同的字符 - 最好的猜测是 VS2008 可以看到它们是不同的,而 linux 没有 - 重写代码以使用不同的方法跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2012-08-18
相关资源
最近更新 更多