Reading non-textual data from a file

Is it possible, using iostream, to read data from a file other than text? I already know how to open a file and read text from it, but I can't find any functions associated with ifstream that read data other than the char data type.

Comments

  • [blue]You mean fstream or ifstream and not iostream right? As long as the file is opened in binary mode, you should be able to use the [b]read[/b] member function of the class to store a chunk of non-text data into a memory location of your choosing. The first argument for the function may be listed as a character pointer but that is not important. For instance if you wrote an integer to a file such as:
    [code]
    ofstream output("temp.txt",ios::binary|ios::out);
    int x;
    output.write((char*)&x,sizeof(int));[/code]
    Then you can read it back in by doing this:
    [code]ifstream input("temp.txt",ios::binary|ios::in);
    int x;
    input.read((char*)&x,sizeof(int));[/code][/blue]
    : Is it possible, using iostream, to read data from a file other than text? I already know how to open a file and read text from it, but I can't find any functions associated with ifstream that read data other than the char data type.
    :

  • Thanks for that, I'll try that now. And yes, I did mean ifstream (I tend to get confused between the lot. 5 years of programming and I still know little :p)

    : [blue]You mean fstream or ifstream and not iostream right? As long as the file is opened in binary mode, you should be able to use the [b]read[/b] member function of the class to store a chunk of non-text data into a memory location of your choosing. The first argument for the function may be listed as a character pointer but that is not important. For instance if you wrote an integer to a file such as:
    : [code]
    : ofstream output("temp.txt",ios::binary|ios::out);
    : int x;
    : output.write((char*)&x,sizeof(int));[/code]
    : Then you can read it back in by doing this:
    : [code]ifstream input("temp.txt",ios::binary|ios::in);
    : int x;
    : input.read((char*)&x,sizeof(int));[/code][/blue]
    : : Is it possible, using iostream, to read data from a file other than text? I already know how to open a file and read text from it, but I can't find any functions associated with ifstream that read data other than the char data type.
    : :
    :
    :

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories