Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,396 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,105 people online right now. Registration is fast and FREE... Join Now!




Templates Help

 
Reply to this topicStart new topic

Templates Help, I'm using em' to try and make a generic file reader

Vextor
21 Sep, 2006 - 04:35 PM
Post #1

D.I.C Regular
Group Icon

Joined: 22 May, 2002
Posts: 288



Thanked: 1 times
Dream Kudos: 25
My Contributions
Ok. I want to make a generic file reader that I can use for a number of projects this semester. I figured i'd use templates to make the job easier but for some reason I cannot get it to work. I'm not sure what's wrong. What I have isn't working for some reason. Unfortunately I have little experience working with bin files so that may be my issue....

Here is my basic idea in a nutshell - what's wrong?


CODE


#include <fstream>
#include <string>
using namespace std;

template <class T>
class FileIO
{
    private:
        fstream file;

    public:
        FileIO();
        void Write(T data);
};



template <class T>
FileIO<T>::FileIO()
{
    file.open("brandon.bin", ios::out | ios::binary);
}

template <class T>
void FileIO<T>::Write(T data)
{
    file.write(static_cast<char*>(data), sizeof(data));
}



int main()
{

    string name;
    FileIO<string> myfile;
    myfile.Write(name);

    return 0;
}



This is assuming a lot as well. I know im missing my .close() and other things....

Am I using the template and/or &fstream write() function right?

Well scratch that. I realized my mistake with the fstream write() function. Is everything else ok?
User is offlineProfile CardPM
+Quote Post

Xing
RE: Templates Help
21 Sep, 2006 - 04:58 PM
Post #2

D.I.C Addict
Group Icon

Joined: 22 Jul, 2006
Posts: 723



Thanked: 2 times
Dream Kudos: 1575
My Contributions
Quickly modified your code. I think it can be improved further but because of shortage of time I am leaving it here.
CODE

#include <fstream>
#include <string>

using namespace std;

template <class T>
class FileIO
{
    private:
        ofstream file;
    public:
        FileIO();
        void Write(const T &data);
};

template <class T>
FileIO<T>::FileIO()
{
    file.open("brandon.bin", ios::out | ios::binary);
}

template <class T>
void FileIO<T>::Write(const T &data)
{
    char *ptr=new char[data.length()+1];
    strcpy(ptr,data.c_str());
    file.write(ptr, strlen(ptr));
    delete[] ptr;
}

int main()
{

    string name("Vextor");
    FileIO<string> myfile;
    myfile.Write(name);
    return 0;
}


This post has been edited by Xing: 21 Sep, 2006 - 05:00 PM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/5/08 02:55AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month