Hi,im having trouble with fstreams at the moment,here is my code

// read contents of file using fstream
// using the ->get() function.
// Ascii files only.

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

main(){

    fstream* file = new fstream( "myfile.txt", fstream::in);
    char aSingleCharacter;


    //this will read a single char from file "myfile.txt"
    aSingleCharacter = (char)file->get();

    // will read contents as long as variable is != EOF
    while(aSingleCharacter != EOF)
    {
        cout << aSingleCharacter;
        aSingleCharacter = (char)file->get();
    }

    file->close();

}

From what i understand,and its probably wrong:

when the file dreams.text is created it should be in the same folder where this code and exe is saved.But it is not there,i even created it and nothing was wrote to it.Is there a problem with the code or is the file created some were on the directory?

Recommended Answers

All 2 Replies

>when the file dreams.text is created it should be in the same folder where this code and exe is saved.

Not necessary. Use absolute path.

fstream* file = new fstream("c:\\dreams.txt", fstream::in);

line 18: >> fstream* file = new fstream( "myfile.txt", fstream::in);

There is absolutely no reason to complicate things more by making fstream object a pointer which has to be allocated. Just create an fstream object fstream file("myfile.txt, ios::in); . Note that ios::in will NOT create a file if it does not already exist. If the file doesn't exist the only way to create it is to open it with ios::out flag or use ofstream instead of fstream.

commented: Good suggestion. +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.