在文件中写入后立即从文件中读取
Reading from file right after Writing in it
我想写入文件然后从中读取并打印结果
我的代码
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
ifstream fd2(argv[1]);
cin>>x;
fd1<<x;
fd2>>y;
cout<<"just read "<<y<<endl;
fd1.close();
fd2.close();
return 0;
}
怎么了?我输入123,它输出"just read -1078463800"
即使你可以同时打开read &写,这个写操作是缓冲的,这意味着它可能不会被写入磁盘,除非您刷新流(或关闭文件)。
当然,下面的代码可以完美地工作:
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
cin>>x;
fd1<<x;
fd1.close();
ifstream fd2(argv[1]);
if (fd2.good())
{
cout << "read OK" << endl;
}
fd2>>y;
cout<<"just read "<<y<<endl;
fd2.close();
return 0;
}
fd2>>y
语句失败,因为还没有从文件中读取任何内容。std::ofstream
缓冲其输出,并且在尝试从文件中读取之前,您没有将缓冲区刷新到磁盘上的文件。
std::ofstream
在以下情况下刷新缓冲区:
-
写入新行
-
它的
flush()
方法被直接调用,或者当std::flush
或std::endl
流到它时。
试试这个:
fd1 << x << flush;
或:
fd1 << x;
fd1.flush();
顺便说一句,您确实应该在此过程中检查错误。std::ofstream
和std::ifstream
构造函数可能无法创建/打开文件。<<
和>>
操作符可能无法写入/读取值。所有这些操作都可以报告您可以检查的错误。例如:
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
int x, y;
std::ofstream fd1(argv[1]);
std::ifstream fd2(argv[1]);
if (!fd1.is_open())
{
std::cout << "cannot create output file" << std::endl;
}
else if (!fd2.is_open())
{
std::cout << "cannot open input file" << std::endl;
}
else if (!(std::cin >> x))
{
std::cout << "invalid input" << std::endl;
}
else if (!(fd1 << x << std::flush))
{
std::cout << "cannot write to output file" << std::endl;
}
else if (!(fd2 >> y))
{
std::cout << "cannot read from input file" << std::endl;
}
else
{
std::cout << "just read " << y << std::endl;
}
return 0;
}
另外:
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
int x, y;
std::ofstream fd1;
std::ifstream fd2;
fd1.exceptions(std::ofstream::failbit);
fd2.exceptions(std::ifstream::failbit);
std::cin.exceptions(std::ifstream::failbit);
try
{
fd1.open(argv[1]);
fd2.open(argv[1]);
std::cin >> x;
fd1 << x << std::flush;
fd2 >> y;
std::cout << "just read " << y << std::endl;
}
catch (const std::ios_base::failure &e)
{
std::cout << "error! " << e.what() << std::endl;
}
return 0;
}
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量