【问题标题】:Read text file into char Array. C++ ifstream将文本文件读入 char 数组。 C++ ifstream
【发布时间】:2011-05-21 08:35:48
【问题描述】:

我试图将整个 file.txt 读入一个字符数组。但是有一些问题,请提出建议=]

ifstream infile;
infile.open("file.txt");

char getdata[10000]
while (!infile.eof()){
  infile.getline(getdata,sizeof(infile));
  // if i cout here it looks fine
  //cout << getdata << endl;
}

 //but this outputs the last half of the file + trash
 for (int i=0; i<10000; i++){
   cout << getdata[i]
 }

【问题讨论】:

  • 或者也许有人可以建议一种将文本文件存储到 char 数组中的更好方法。
  • 如果您在除玩具应用程序之外的任何其他应用程序中执行此操作,请确保您设置了防止无限内存分配的保护措施。
  • 您似乎遗漏了一些分号。

标签: c++ arrays char ifstream


【解决方案1】:
std::ifstream infile;
infile.open("Textfile.txt", std::ios::binary);
infile.seekg(0, std::ios::end);
size_t file_size_in_byte = infile.tellg();
std::vector<char> data; // used to store text data
data.resize(file_size_in_byte);
infile.seekg(0, std::ios::beg);
infile.read(&data[0], file_size_in_byte);

【讨论】:

    【解决方案2】:

    使用std::string:

    std::string contents;
    
    contents.assign(std::istreambuf_iterator<char>(infile),
                    std::istreambuf_iterator<char>());
    

    【讨论】:

    • ...记住这个咒语总是很困难。不太直观。 PS。由于 OP 请求了一个 char 数组,contents.c_str() 可以使用。
    【解决方案3】:

    如果您打算将整个文件吸入缓冲区,则无需逐行读取。

    char getdata[10000];
    infile.read(getdata, sizeof getdata);
    if (infile.eof())
    {
        // got the whole file...
        size_t bytes_really_read = infile.gcount();
    
    }
    else if (infile.fail())
    {
        // some other error...
    }
    else
    {
        // getdata must be full, but the file is larger...
    
    }
    

    【讨论】:

    • 如果文件大于10000 chars怎么办?
    • .... 你打算在那里做什么?声明另一个更大的字符数组并再次读取?错了,不是吗?
    【解决方案4】:

    每次读取新行时,都会覆盖旧行。保留一个索引变量 i 并使用 infile.read(getdata+i,1) 然后递增 i。

    【讨论】:

    • read(..., 1) 一次读取一个字符...非常低效。
    • infile.seekg(0,ios::end);int len = infile.peekg();infile.seekg(0,ios::beg);infile.read(getdata,len);
    【解决方案5】:

    您可以使用 Tony Delroy 的答案并结合一个小函数来确定文件的大小,然后创建该大小的 char 数组,如下所示:

    //Code from Andro in the following question: https://stackoverflow.com/questions/5840148/how-can-i-get-a-files-size-in-c
    
    int getFileSize(std::string filename) { // path to file
        FILE *p_file = NULL;
        p_file = fopen(filename.c_str(),"rb");
        fseek(p_file,0,SEEK_END);
        int size = ftell(p_file);
        fclose(p_file);
        return size;
    }
    

    那么你可以这样做:

    //Edited Code From Tony Delroy's Answer
    char getdata[getFileSize("file.txt")];
    infile.read(getdata, sizeof getdata);
    
    if (infile.eof()) {
        // got the whole file...
        size_t bytes_really_read = infile.gcount();
    }
    else if (infile.fail()) {
        // some other error...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 2012-11-13
      • 2012-10-20
      • 2015-07-11
      • 2017-01-20
      • 2017-01-13
      • 1970-01-01
      • 2011-08-01
      相关资源
      最近更新 更多