我想编写一个简单的函数,它将文件名作为参数,然后返回一个包含文本文件中字符的常量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指针打印文本时,它可以工作。但是当指针传递到函数外部并尝试使用它时,输出是控制台中每个字符的白框。我尝试了很多不同的东西,没有任何东西能让它发挥作用。我不明白为什么它在函数内部起作用,但它在外面不起作用。
答案 0 :(得分:0)
你可以做一些花哨的事情并使用mmap()(Linux假设)将文件映射到虚拟内存中。这将推迟实际从磁盘读取文件的点,并将节省内存。它也适用于任意长度的文件。
答案 1 :(得分:0)
您正在返回指向矢量底层元素数组的指针。但是,由于向量是局部变量,因此当函数Get_Text
返回时,它会超出范围。自动变量在超出范围时会被破坏,与它们相关的任何内容也会因此被破坏。返回矢量本身甚至更好的字符串是更好的选择。
如果您必须通过返回char*
来执行此操作,请使用std::unique_ptr<char[]> text(new char[SIZE])
。返回text.get()
并返回main
时,您有责任致电delete [] ptr
。