user1845360
user1845360

Reputation: 857

Creating output file in C++ Visual Studio 2010

I have a C++ project which I initially compiled with g++. Now, I am trying to make it work in Visual Studio 2010 and the problem is that the regular commands that create an empty output file for writing:

#include <fstream>
using namespace std;

ofstream fout("afile.txt");
fout<<"write someting"<<endl;
fout.close();

will not work in VS2010 (no file is created). Even if the file already exists nothing is written on it.

So, any ideas what is the correct way of opening a file for writing from C++ in VS2010 ?

Upvotes: 2

Views: 29751

Answers (4)

user6408370
user6408370

Reputation: 1

manually add afile.txt into the same location with your source file, and then run the your program. text will be written into the file. But make sure afile.txt file is not open when you run the program

Upvotes: -1

MikhailJacques
MikhailJacques

Reputation: 1

I had the same problem which puzzled me for a few minutes. Examine your project directory. I bet you will find your file in there. If not, then you need to specify a working directory for either debug or release modes. In MS Visual Studio you can do so by clicking the Properties on the Project menu and then specifying in the Configuration properties in lets say a Debugging tab in the Working directory field the directory from which you want your project to be launched.

Upvotes: -2

Caribou
Caribou

Reputation: 2081

My suspicion is that the file is created somewhere other than you expected - Check out where the working directory is pointing. This is 2012, but it is very similar if not the same... Right click on the project in vs2010, and select properties, Then select debugging and look at the working directory:

enter image description here

Alternitively, build it, and copy the app to a directory you create - Then run it on the command line to check whether its a permissions problem.

Upvotes: 4

MartenBE
MartenBE

Reputation: 802

Following code works fine by me:

#include <fstream>
using namespace std;

int main(){
    ofstream fout("afile.txt");
    fout << "write someting"<<endl;
    fout.close();
    return 0;
}

You didn't use the main method (strange that it didn't give any syntax errors). Make sure when you creat a project like this it is a ConsoleApplication and it's an empty project (you can check this option under "Additional Options" in the Win32 Application Wizard (The wizard used to create a project).

Standard C++ should work in Visual Studio. If you want to be sure you're using only standard C++ code, you can always use the /Za compiler option (See http://msdn.microsoft.com/en-us/library/0k0w269d.aspx)

Upvotes: 1

Related Questions