【发布时间】: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::strng、std::getline和std::string::operator+=。