无法用C ++编写文件

时间:2009-10-12 22:21:07

标签: c++ windows-7 writefile

我正在尝试最基本的东西....用C ++编写一个文件,但文件没有写入。我也没有任何错误。也许我错过了一些明显的东西......或者是什么?

我认为我的代码有问题,但我也尝试过在网上找到的样本,但仍然没有创建文件。

这是代码:

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

我之前也尝试过手动创建文件,但根本没有更新。

我正在运行Windows 7 64位,如果这与此有关。这就像文件写入操作是完全禁止的,并且没有显示错误消息或异常。

6 个答案:

答案 0 :(得分:3)

您需要以写入模式打开文件:

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

确保查看第二个参数的其他选项。如果你正在编写二进制数据,那么你需要ios::binary

您应该在打开后检查流:

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

更新

AraK是对的,我忘了默认情况下ofstream处于写入模式,所以这不是问题。

也许您根本没有对目录的写入/创建权限? Win7默认许多具有“拒绝所有”特殊权限的目录。或者该文件可能已存在并且是只读的?

答案 1 :(得分:2)

通过转动斜线开始。
即便是Windows也能理解斜线是相反的。

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

您可以测试是否有任何错误:

if (!myfile)
{
    std::cout << "Somthing failed while opening the file\n";
}
else
{
    myfile << "Writing this to a file.\n";
    myfile.close();
}
  • 确保目录存在。
  • 如果文件存在,请确保它是可写的(由您)
  • 检查您正在写入的目录是否可写(由您)

答案 2 :(得分:1)

您是否了解过Windows Vista和7中的UAC(用户帐户控制)和UAC虚拟化/数据重定向?您的文件可能实际上在虚拟商店中。

User Account Control Data Redirection

您的示例输出目录位于用户中,因此我不认为这会是问题所在,但是如果您不注意它,这可能是值得一提的事情,这可能非常令人沮丧!

希望这有帮助。

答案 3 :(得分:1)

此代码应捕获任何错误。如果遇到任何错误,很可能是权限问题。确保您可以读取/写入您正在创建文件的文件夹。

#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;
}

更新: 我只是在Windows 7 Enterprize下测试我的代码,它第一次失败(设置了失败位)。然后我关闭用户帐户控制(UAC)并再次测试并写入文件。这可能与您所看到的问题相同。要关闭UAC,请转到:

控制面板(按小图标查看)|用户帐户|更改用户帐户控制设置。将其设置为从不通知然后单击确定按钮。您必须重新启动才能使更改生效。

我很好奇如何让它与UAC合作,我会调查一下。

答案 4 :(得分:0)

试试这个:

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

//find the error code and look up what it means.
}

答案 5 :(得分:0)

使用FileMon并查找进程中失败的WriteFile调用。

相关问题