-5

I am trying this code for a few first times only. I am not able to get to the root of the error.

Here is the code:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    fstream file;
    file.open("C:\\Users\\AfzaalAhmad\\Documents\\text.txt");
    return 0;
}

The file is present at the location. Here is a screenshot of the file system.

Screenshot of the file system

There is no exception in this case, but the file is never opened!

Where am I missing code?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103

1 Answers1

5

The command you've written will open a handle to a file at that location. In order to do anything with it, you'll need some sort of read or write operation. Probably your code is working fine :)

For example, following your file.open("...") line:

file << "This is some text to send to my now open file\n";
...
file.close();
chrisb2244
  • 2,940
  • 22
  • 44
  • You're welcome. I edited my answer with some examples - the other answer from @karakale is likely to be helpful for you there :) – chrisb2244 Feb 01 '14 at 15:25
  • I would have tried out his tutorial link, but I don't know why that site is down since 3 days here: http://imgur.com/RveTZfP .. – Afzaal Ahmad Zeeshan Feb 01 '14 at 15:28
  • 1
    @AfzaalAhmadZeeshan: No, you should use [a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Lightness Races in Orbit Feb 01 '14 at 15:30
  • Well, I confess to having used cplusplus.com quite a bit, but I'm told it's not very good. As @LightnessRacesinOrbit points out, SO has a question about the best C/C++ books with some pretty extensive answers. – chrisb2244 Feb 01 '14 at 15:48
  • @chrisb2244: The reference, nowadays, is fairly accurate and well maintained, but the forum contributions are not inherently peer reviewed, and because of the name of the site you get a _lot_ of entry-level contributions that will teach you bad practices and bugs, written by those who don't yet know any better. It's a vicious cycle, really. The tutorial is _okay_, but no substitute for a full book written by a prestigious author. – Lightness Races in Orbit Feb 01 '14 at 15:50