cpp文件写入指针不发指向文件尾部
本帖最后由 空蓝 于 2024-4-17 16:35 编辑#include <fstream>
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main()
{
fstream fp("test.txt", ios::in | ios::out);
if (!fp)
{
cerr << "打开文件失败!" << endl;
return 0;
}
fp.seekp(ios::end); // 使得文件指针指向文件头 ios::end 则是文件尾。
fp << "IloveFishc.com!";
static char str;
fp.seekg(ios::beg); // 使得文件指针指向文件头 ios::end 则是文件尾。
fp >> str;
cout << str << endl;
fp.close();
return 0;
}
使用 fp.seekp(ios::end);想把写入指针指向文件末尾,并写入 IloveFishc.com实际上是在第三个字符处开始写入的.
原文内容:123456789
写入后内容:12IloveFishc.com!
你好,看起来你想打开一个文件并将指针定位到文件的末尾。在C++中,你可以使用seekp函数来实现这个目标。下面是一个示例代码:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fp("test.txt", ios::app);
if (!fp) {
cerr << "无法打开文件" << endl;
return 1;
}
// 将指针定位到文件的末尾
fp.seekp(0, ios::end);
// 在文件末尾写入数据
fp << "Hello World!" << endl;
fp.close();
return 0;
}
首先,我们打开文件时使用了`ofstream`而不是`fstream`,因为你只是想写入数据而不是读取数据。我们还使用了`ios::app`标志来将指针定位到文件的末尾。
然后,我们使用`seekp`函数将指针移动到文件的末尾。`seekp`函数接受两个参数:第一个参数是要移动的偏移量,第二个参数是从哪个位置开始移动。在这里,我们将偏移量设置为0,表示从当前位置移动0个字节,将指针定位在文件末尾。
最后,我们使用`fp << "Hello World!" << endl;`将数据写入文件的末尾。
希望这可以解决你的问题!如果有任何疑问,请随时提出。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 本帖最后由 jackz007 于 2024-4-17 16:56 编辑
#include <fstream>
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main()
{
fstream fp("test.txt", ios::in | ios::out);
if (!fp)
{
cerr << "打开文件失败!" << endl ;
return 0;
}
fp.seekp(0L , ios::end) ; // 此处有修改
fp << "IloveFishc.com!" ;
static char str;
fp.seekg(0L , ios::beg) ; // 此处有修改
fp >> str;
cout << str << endl ;
fp.close() ;
return 0 ;
}
别忘记每次运行都得重新初始化文件 "test.txt" 的内容。 jackz007 发表于 2024-4-17 16:53
别忘记每次运行都得重新初始化文件 "test.txt" 的内容。
谢谢老师 解决了,了解了一下seekp函数
页:
[1]