gpt4 book ai didi

c++ - c++ 中的 ios::app、out 和 trunc 有什么区别?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:53 39 4
gpt4 key购买 nike

我知道默认的文件打开模式是out。而且我认为 out 会覆盖文件中的数据,但在下面的代码中,age data 不会覆盖 name data

#include <fstream> 
#include <iostream>
using namespace std;

int main () {

char data[100];

// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);

// write inputted data into the file.
outfile << data << endl;

cout << "Enter your age: ";
cin >> data;
cin.ignore();

// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();

// open a file in read mode.
ifstream infile;
infile.open("afile.dat");

cout << "Reading from the file" << endl;
infile >> data;

// write the data at the screen.
cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.
infile.close();

return 0;

然后我对文件的三种打开方式——app、out、trunc感到困惑。

如果我在名字中输入“Zara”和年龄“9”,输出应该是“9ara”。然而,事实并非如此。是“Zara 9”。

最佳答案

ios::outstd::ofstream 的默认模式,这意味着可以使用输出操作(即可以写入文件)。

ios::app(append 的缩写)意味着不是从头覆盖文件,而是在文件末尾完成所有输出操作。这仅在文件也打开输出时才有意义。

ios::trunc(truncate 的缩写)表示当文件打开时,旧内容会立即被删除。同样,这仅在文件也打开输出时才有意义。

您的代码仅使用默认的 ios::out 模式。所以它从文件的开头开始写入,但不会删除旧内容。因此新内容将覆盖已有的内容——如果文件最初为 10 个字节长,而您写入了 3 个字节,结果将是您写入的 3 个字节后跟原始内容的其余 7 个字节。更具体地说,如果文件最初包含:

Firstname Lastname
30

然后您编写 FN LN,然后是 20(每个后面都有换行符),生成的文件将如下所示:

FN LN
20
Lastname
30

因为您只覆盖了文件的前 9 个字节(假设是 Unix 风格的换行符)。

打开文件后,文件的所有输出都会依次写入,除非您使用 outfile.seekp() 转到不同的位置。它不会为您编写的每件事返回到文件的开头。如果使用 ios::app,则 seekp() 无效;然后每次写入都在文件末尾。

关于c++ - c++ 中的 ios::app、out 和 trunc 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085781/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com