代码之家  ›  专栏  ›  技术社区  ›  Thorgeir

无法在C++中写入文件

  •  4
  • Thorgeir  · 技术社区  · 16 年前

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

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

    这是代码:

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

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

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

    6 回复  |  直到 15 年前
        1
  •  2
  •   Tim Sylvester    16 年前

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

    ios::binary

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

    ofstream

        2
  •  2
  •   Lightness Races in Orbit    15 年前


    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();
    }
    
        4
  •  1
  •   cchampion    16 年前

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

        5
  •  0
  •   Paul Nathan    16 年前

    if( ! myfile)
    {
    cerr << "You have failed to open the file\n";
    
    //find the error code and look up what it means.
    }
    
        6
  •  0
  •   Alex Budovski    16 年前