在文件中设置了位置,不能读取它
Set position in file and cannot read it back
我创建了一个文件,我将读和写位置都移动到5,我读取位置,我得到的是一个无效的位置。为什么?
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fname = "test.txt";
{
fstream fs(fname);
fs << "abcdefghijklmnopqrstuvwxyz";
}
fstream fs(fname);
streamoff p = 5;
fs.seekg(p, ios_base::beg);
fs.seekp(p, ios_base::beg);
const streamoff posg = fs.tellg();
const streamoff posp = fs.tellp();
cerr << posg << " = " << posp << " = " << p << " ???" << endl;
return 0;
}
结果:-1 = -1 = 5 ??
你没有正确地创建文件,所以你打开一个文件进行读写,而没有指定打开的选项,在这种情况下,它认为文件已经存在,因此它无法打开。
- 第二个错误是你将字符串传递给fstream的open函数,该函数接受const字符串,结果失败,因此你将其转换为char*与string的c_str成员函数。
法则是拇指总是检查打开是否成功。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string fname = "test.txt";
fstream fs(fname.c_str(), ios::out | ios::in | ios::binary | ios::trunc);
if(fs.fail())
cout << "Failed to open file" << endl;
fs << "abcdefghijklmnopqrstuvwxyz";
streamoff p = 5;
fs.seekg(p, ios_base::beg);
fs.seekp(p, ios_base::beg);
const streamoff posg = fs.tellg();
const streamoff posp = fs.tellp();
cerr << posg << " = " << posp << " = " << p << " ???" << endl;
fs.close();
return 0;
}
- 注意,如果你不打开标志(ios::trunc, out, in),只需在你的项目目录下手动创建一个名为"test.txt"的文件。
问题是你的文件从来没有正确地写在第一个地方,因为你使用的是std::fstream
,当打开一个不存在的文件时,它的默认模式是ios::out|ios::in
(参见std::basic_filebuf::open
和std::basic_fstream::open
使用的默认参数)。
要解决这个问题,只需在写入文件时使用std::ofstream
而不是std::fstream
:
{
ofstream fs(fname);
fs << "abcdefghijklmnopqrstuvwxyz";
}
相关文章:
- 将值从另一个数组写入数组,不包括不需要的值 C++
- 使用 cv::不扭曲不失真和居中图像
- C 与C++编译不兼容 - 不命名类型
- 类定义怎么能不占用内存?
- 如何在不指定不必要的模板参数的情况下使用模板类的成员类型
- 一个倒梯形,但如果输入高度对于宽度来说太大,那么它应该报告,不可能("不可能的形状"是什么)
- 模板参数是哪些类型的值?我能(不)用它们做什么
- 为什么SDL_RWFromFile(文件,"w+")不能像它应该的那样读写?它只打开文件进行写入
- 将不相等的线读入向量的向量
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- glTranslatef拉伸我的球体,我怎么能不拉伸它就平移球体
- 在嵌套CWND衍生的类中,不关注不改变选项卡键
- 你能不能使用 JNI 在从 java 调用的 c++ 函数中创建一个新的 JVM
- 在使用cin.get()时C++,我怎么能不限制用户可以输入的字符数
- 我能不能做一个unique_ptr不拥有其尖头对象的所有权
- LNK2005,我不知道我能做些什么来解决这个问题
- 一个C++11数组怎么能不存储它的大小呢
- 读取文件而不将整个内容读入内存
- 怎么能不工作,但马洛克可以
- 能不能回式混?或者变通的解决方案