c++Converting text file to constant char pointer

This question already has an answer here:

  • Read whole ASCII file into C++ std::string

    7 answers

I wanted to write a simple function that will take a file name as an argument and then return a constant char pointer that contains the characters in the text file.

#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;
}

When I print the the text with the *char pointer inside of my function it works. But when the pointer is passed outside of the function and I try to use it, the output is a white box for each character in the console. I have tried a bunch of different things and nothing gets it to work. I don't understand why it works inside of the function but it doesn't work outside.

You could do something fancy and use mmap() (Linux assumed) to map the file into virtual memory. That would postpone the point at which the file was actually read from disk and would save memory. It would also work on arbitrary length files.

You're returning a pointer to the vector's underlying element array. However, since the vector is a local variable it goes out of scope when the function Get_Text returns. Automatic variables get destroyed when they go out of scope, whatever is associated with them also get thereby destroyed. Returning the vector itself or even better a string is a better option.

If you absolutely have to do this by returning a char*, then use std::unique_ptr<char[]> text(new char[SIZE]). When returning return text.get() AND in main you have the responsibility of calling delete [] ptr.

Related Articles
  • This question already has an answer here: how to convert System::String to const char*? 1 answer I am using Visual C++ 2008's GUI creator to make a user interface. When a button is clicked, the following function is called. The content is supposed to
  • Possible Duplicate: Convert std::string to const char* or char* void Foo::bar(const std::string& foobar) { // ... const char* foobar2 = (char*)foobar; // ... } That does not work and I get an error during compilation about invalid casting. Is there s
  • #include <windows.h> int WINAPI WinMain(HINSTANCE hInsance,HINSTANCE hPrevInstance,PSTR cmdLine,int showCmd){ MessageBox(0,"First Win32 Program","Window Tittle",MB_OK); } error C2664: 'MessageBoxW' : cannot convert parameter 2 fr
  • I am getting an error when I run this piece of code string line; getline (myfile,line); char file_input[15]; strncpy(file_input, line, 6); cout << line << endl; Error - cannot convert 'std::string' to 'const char*' for argument '2' to 'char* s
  • Hi can any one tell what wrong with this code ?. string s=getString(); //return string if(!strcmp(s,"STRING")){ //Do something } while compiling I am getting the error like error: cannot convert 'std::string' to 'const char*' for argument '1' to
  • I am trying to break a string into integer and characters using below codes. in the first section on the immediate printing I got the right output but later it is wrong. int Lottery::calcInvOdds(string ruleConstraint){ const char * sorted; const char
  • I've been at it all night just trying to get a simple program to read in a text file and then copy it/write it back into a binary format. My code looped through the text doc, got the data, put it in the buffer and wrote it back out. Heck I even hard
  • I have this lab problem that I've now been stuck on for three days and I'm pretty sure after countless googling and trying pretty much everything I can find, that I've just confused myself to the point of being utterly lost. I'm not sure if this is w
  • This is my first post here. I am writing a program in C++ using file handling in which I have a given text file and I wish to delete everything in the file beyond a certain point at which my pointer is, after which the pointer should return to the sa
You Might Also Like