Unable to write file in C++
Asked Answered
P

6

6

I'm trying to to the most basic of things .... write a file in C++, but the file is not being written. I don't get any errors either. Maybe I'm missing something obvious ... or what?

I thought there was something wrong with my code, but I also tried a sample I found on the net and still no file is created.

This is the code:

ofstream myfile;
myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt");
myfile << "Writing this to a file.\n";
myfile.close();

I've also tried creating the file manually beforehand, but it's not updated at all.

I'm running Windows 7 64bit if that has got something to do with this. It's like file-write operations are completely forbidden and no error messages or exceptions are shown.

Panjabi answered 12/10, 2009 at 22:21 Comment(4)
I know this is not a solution, but this happened with me before. Just replace ofstream with fstream.Jerz
Are you sure there is a folder named "Documents" there? If I'm not mistaken, it's normally named "My Documents"...Atwekk
@Jerry it changed to just "Documents" since Vista.Siskind
When you copy this snippet of code, change the path ;)Litchi
C
3

You need to open the file in write mode:

myfile.open ("C:\\Users\\Thorgeir\\Documents\\test.txt", ios::out);

Make sure to look at the other options for that second argument, as well. If you're writing binary data you'll need ios::binary for example.

You should also be checking the stream after opening it:

myfile.open(...
if (myfile.is_open())
    ...

Update:

AraK is right, I forgot that an ofstream is in write mode by default, so that's not the problem.

Perhaps you simply don't have write/create permissions to the directory? Win7 defaults a lot of directories with special permissions of "deny all". Or perhaps that file already exists and is read-only?

Castalia answered 12/10, 2009 at 22:24 Comment(1)
@Tim Good point, but std::ios::out is set by default in the constructor of ofstream.Jerz
A
2

Start off by turning that slash around.
Even Windows understands the slash being the other way around.

ofstream myfile("C:/Users/Thorgeir/Documents/test.txt");

You could test if there are any errors:

if (!myfile)
{
    std::cout << "Somthing failed while opening the file\n";
}
else
{
    myfile << "Writing this to a file.\n";
    myfile.close();
}
  • Make sure the directory exists.
  • If the file exists make sure it is writeable (by you)
  • Check the directory you are writing into is writeable (by you)
Away answered 12/10, 2009 at 23:11 Comment(3)
Why recommend using a path separator that's not native to the target platform? Especially when it solves nothing? Odd.Baptism
@Tomalak: Not really. The use of the '\' is error prone at best because it is an escape character (there is no compile time checking to make sure it is correctly used). MS recognized the problem a decade ago and added support for the '/' the plan was to move to be compatible with other OS's. Unfortunately they got stuck in the backward compatibility problem/Away
@Tomalak: Then you are luck y to work with a group of developers that never make mistakes. I on the other hand have worked with a lot of crappy developers (not my current fellow employees) had have had to fix the missing extra backslash many time. Also cutting and pasting a directory from the code into a shell now does not work as cleanly as you want.Away
J
1

Have you read about UAC (User Account Control) and UAC Virtualization / Data Redirection in Windows Vista and 7? It's possible that your file is actually in the Virtual Store.

User Account Control Data Redirection

Your example output directory is in Users, so I wouldn't think this would be the issue, but it's a possibility worth mentioning and something that can be very frustrating if you're not looking out for it!

Hope this helps.

Jessabell answered 12/10, 2009 at 22:52 Comment(0)
M
1

This code should catch any error. Most likely it's a permissions thing if any errors are encountered. Make sure you can read/write to the folder you're creating the file in.

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

bool CheckStreamErrorBits(const std::ofstream& ofile);

int _tmain(int argc, _TCHAR* argv[]) {
 std::ofstream ofile("c:\\test.txt");
 if(ofile.is_open()) {
  CheckStreamErrorBits(ofile);  
  ofile << "this is a test" << std::endl;
  if(CheckStreamErrorBits(ofile)) {
   std::cout << "successfully wrote file" << std::endl;
  }
 }else {
  CheckStreamErrorBits(ofile);
  std::cerr << "failed to open file" << std::endl;
 }

 ofile.close();
 return 0;
}

//return true if stream is ok.  return false if stream has error.
bool CheckStreamErrorBits(const std::ofstream& ofile) {
 bool bError=false;
 if(ofile.bad()) {
  std::cerr << "error in file stream, the bad bit is set" << std::endl;
  bError=true;
 }else if(ofile.fail()) {
  std::cerr << "error in file stream, the fail bit is set" << std::endl;
  bError=true;
 }else if(ofile.eof()) {
  std::cerr << "error in file stream, the eof bit is set" << std::endl;
  bError=true;
 }
 return !bError;
}

Update: I just test my code under Windows 7 Enterprize and it failed the first time (fail bit was set). Then I turn off User Account Control (UAC) and tested again and it wrote the file. That is probably the same problem you're seeing. To turn off UAC go to:

Control Panel (view by Small icons) | User Accounts | Change User Account Control settings. Set it to Never notify then click OK button. You will have to restart for the changes to take affect.

I'm curious how to make it work with UAC on, i'll look into that.

Millenary answered 18/10, 2009 at 2:43 Comment(0)
C
0

Try this:

if( ! myfile)
{
cerr << "You have failed to open the file\n";

//find the error code and look up what it means.
}
Clinician answered 12/10, 2009 at 23:6 Comment(2)
It's worth mentioning in your answer that this is Microsoft-specific. C++ has no "error codes" for stream failures; only the failure modes.Baptism
@Tomalak: Perhaps, but the questioner was using Windows, so, at the time, I was endeavoring to help them.Clinician
G
0

Use FileMon and look for failed WriteFile calls from your process.

Griffey answered 20/11, 2009 at 3:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.