【问题标题】:Why text file created is blank?为什么创建的文本文件是空白的?
【发布时间】:2016-04-13 23:31:48
【问题描述】:

我的代码是

#include <iostream.h>
#include <conio.h>
#include <fstream.h>
#include <stdio.h>

struct info
{
    char product_name[100], Seller_Name[100], DOP[30];
    int  price;
}data;

void main()
{
    ofstream fout("code.txt",ios::out);
    fout<< "ofstream fout(\"data.dat\",ios::binary|ios::out);\n";
    while(1)
    {
        cout <<  "Enter Product Name: ";
        gets(data.product_name);
        cout<<"Enter Seller Name: ";
        gets(data.Seller_Name);
        cout<<"Enter Date of Purchase: " ;
        gets(data.DOP);
        cout<<"Enter Price:" ;
        cin>>data.price;
        fout<<"strcpy(data.product_name,"<<data.product_name<<");";
        fout<<"nstrcpy(data.Seller_Name,"<<data.Seller_Name<<");";
        fout<<"nstrcpy(data.DOP,"<<data.DOP<<");";
        fout<<"nstrcpy(data.price,"<<data.price<<");";
        fout<<"fout.write((char*)&data,sizeof(info));n";
    }
}

我正在开发一个软件并为其制作示例数据。所以我做了这个应用程序,所以我只需要复制语句而不必再次编写它。第一次成功了,现在不行了。

【问题讨论】:

  • 您的空格键是否有问题,因为代码似乎没有任何缩进
  • 你为什么要把stdioiosteam混在一起?
  • –1 尝试发布真实代码
  • while循环什么时候结束?
  • 我认为nstrcpy -> \nstrcpy(和其他地方)。添加这些新行也会刷新缓冲区。

标签: c++ file-handling


【解决方案1】:

您的缓冲区可能没有被刷新。

试试这个:

while(1){
  //...
  fout.flush();
}

【讨论】:

  • 非常感谢。我用过它,它奏效了......你能告诉我它是什么以及我为什么用它吗?
  • @AyushMahajan ofstream 是一个对象。它的工作是为您写入文件。但是,文件 I/O 在机器上是一项昂贵的操作。为了更高效,ofstream 对象保存在内部缓冲区中。你可以认为这是一个临时的字符数组。它将使用此缓冲区一次写入文件。从长远来看,这更有效。但是,如果您的缓冲区不够大而无法自动刷新,或者您没有使用 std::endl 之类的东西为您刷新,您将看不到文件中的数据。
【解决方案2】:

完成后尝试关闭输出流

fout.close()

查看此处了解更多信息: http://www.cplusplus.com/doc/tutorial/files/

短:

数据被缓冲并且仅作为优化定期写入。 关闭文件会刷新缓冲区(写入所有内容)并为其他进程释放文件。

【讨论】:

  • 这确实可行,因为关闭文件会刷新缓冲区。
  • 是的,关闭文件会刷新缓冲区。要点是在“完成”文件时关闭文件。完成由作者决定。
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 2015-08-18
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-22
  • 2014-03-31
相关资源
最近更新 更多