简体   繁体   中英

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 ?

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:

在此处输入图片说明

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.

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 )

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM