【问题标题】:Converting text file to constant char pointer [duplicate]将文本文件转换为常量字符指针[重复]
【发布时间】:2013-12-31 21:54:54
【问题描述】:

我想编写一个简单的函数,它将文件名作为参数,然后返回一个包含文本文件中字符的常量 char 指针。

#include <fstream>
#include <vector>
#include <iostream>
#include "text.h"

//function to get the size of a file
unsigned int Get_Size(const char * FileName){
    std::ifstream filesize(FileName, std::ios::in|std::ios::ate);

    unsigned int SIZE = filesize.tellg();

    filesize.close();

    return SIZE;
}

//Takes a file name then turns it into a c-style character array
const char * Get_Text(const char * FileName){

    //get size of the file
    unsigned int SIZE = Get_Size(FileName);


    std::ifstream file(FileName, std::ios::in);

    //I used a vector here so I could initialize it with a variable
    std::vector<char> text(SIZE);

    //here is where I loop through the file and get each character
    //and then put it into the corresponding spot in the vector
    std::streampos pos;
    for(int i = 0; i<SIZE; i++){
            pos=i;
        file.seekg(pos);
        text[i] = file.get();
    }

    //I manually added the terminating Null character
    text.push_back('\0');

    //I set the pointer equal to the address of the first element in the vector
    const char * finalText = &text[0];

    file.close();

    //this works    
    std::cout<<finalText<<std::endl;

    return finalText;
};

int main(){

    //this does not work
    std::cout<<Get_Text("Text.txt")<<std::endl;

    return 0;
}

当我在函数内部使用 *char 指针打印文本时,它可以工作。但是当指针被传递到函数之外并且我尝试使用它时,输出是控制台中每个字符的白框。我尝试了很多不同的东西,但没有任何效果。我不明白为什么它在函数内部起作用,但在外部不起作用。

【问题讨论】:

  • 为什么这个标签是c?哪个版本的 C 标准库提供 std::vector
  • 另外,您正在返回指向向量内部的数据,但是当函数返回时向量被破坏,因此您会得到垃圾(和未定义的行为)。最好将文件读入动态分配的缓冲区 (new string[size]) 并返回该缓冲区。更好的是,只需使用std::strngstd::getlinestd::string::operator+=

标签: c++ pointers io iostream


【解决方案1】:

您正在返回一个指向向量底层元素数组的指针。然而,由于向量是一个局部变量,当函数Get_Text 返回时,它会超出范围。自动变量在超出范围时会被破坏,与它们相关的任何东西也会因此而被破坏。返回向量本身甚至更好的字符串是更好的选择。

如果您绝对必须通过返回 char* 来执行此操作,请使用 std::unique_ptr&lt;char[]&gt; text(new char[SIZE])。返回时返回text.get() AND 在main 中,您有责任调用delete [] ptr

【讨论】:

    【解决方案2】:

    您可以做一些花哨的事情并使用 mmap()(假设是 Linux)将文件映射到虚拟内存中。这将推迟从磁盘实际读取文件的时间并节省内存。它也适用于任意长度的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多