0

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?

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

>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);
0

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.

Votes + Comments
Good suggestion.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.