从文件中读取和写入int对
Read and write int pairs from file
我正在尝试从文件中读取并编写一系列int对。该文件看起来像这样:
0 6
12 24
48 33
23 24
80 79
我的目标是将每对读成一个结构:
struct foo {
int a;
int b;
}
,然后将每个结构推入堆栈。但是,Fstreams已被证明很难处理此任务。现在,我的文件读取代码看起来像这样:
std::fstream fileStream(file, std::ios::in);
int a, b;
while (fileStream >> a >> b) {
myStack.push({ a, b });
}
,我的输入可能看起来像这样(我必须单独这样做,因为我使用的是...):
inputFoo(foo bar) {
std::fstream fileStream(file, std::ios::out);
fileStream << bar.a << " " << bar.b;
}
但是,我觉得这不是我应该有效,安全地这样做的方式。我也有一个功能可以检查文件是否已经存在,但我不确定一个功能也可以工作:
bool fileExists() {
std::ifstream stream;
return stream.good();
}
真正做到这一点的最佳方法是什么?
确实喜欢这个
std::ifstream fileStream(file, std::ios::in);
while (!fileStream.eof()) {
foo f;
fileStream >> f.a>> f.b
myStack.push(f);
}
循环将结束阅读整个文件
写作将就像这样
std::ofstream fileStream(file, std::ios::in);
while (!myStack.isEmpty()) {
foo f;
f=myStack.pop();
fileStream << f.a<<" "<< f.b<<endl;
}
您不需要fileExists()
函数。该功能中的流甚至没有打开。只需检查一下:
std::fstream fileStream(file, std::ios::in);
if(!fileStream.is_open())
{
// handle the error
}
现在,如果您愿意,很少有建议不会改变逻辑:
- 使用
std::ifstream
进行输入,您可以省略std::ios::in
参数 - 使用
std::ofstream
进行输出,您可以省略std::ios::out
参数 过载
<<
和>>
的CC_7:struct foo { int a; int b; foo() : a(0), b(0) {} // default constructor to make it a little more c++ and less c friend std::istream &operator>>(std::istream &is, foo &f); std::ostream &operator<<(std::ostream &os) { return os << a << " " << b; } }; // Both can be friend, only operator<< can be member std::istream &operator>>(std::istream &is, foo &f) { return is >> f.a >> f.b; }
您不仅可以传递文件流,还可以通过
std::cin
和std::cout
(可能对调试和控制台输入输出可能很有用)。您会这样阅读:foo f; while(fileStream >> f) myStack.push(f);
写更简单:
fileStream << bar;
关于您的评论,这是我唯一想到的:
const std::string filePath = "file.txt";
std::ifstream ifs(filePath);
if(ifs.is_open())
{
// read
}
else
{
std::ofstream ofs(filePath);
// write
}
相关文章:
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- C++ 中文件输入输出中的长长 v/s int
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 如何读取 TXT 文件并仅将 int 存储在 C 中
- 如何检测将文本文件读入 int 数组的新行
- C++快速将 int 数组内容转储到文本文件中
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- 如何将逗号分隔的文件读取为 2D int 数组?
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- C++将文件行分离为String和Int
- C ++ txt 文件成数组逐行字符串和 int 用于纸牌游戏
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 如何使用fstream从.txt文件C++中取出int值
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 利用输入文件中的数据(字符串和int)并在循环中利用
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何通过头文件中的函数初始化 const int 数组?
- 无法一次从二进制文件中读取一个 int
- 我可以对"int 文件 = open(path, flag);"做点什么吗?
- 使用 c++ 时从二进制文件中读取 int 不正确