首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在c++中,ios::app、out和trunc之间有什么不同?

在c++中,ios::app、out和trunc之间有什么不同?
EN

Stack Overflow用户
提问于 2018-01-03 22:01:18
回答 2查看 27.8K关注 0票数 9

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

代码语言:javascript
运行
复制
#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;

然后我对文件的三种开放模式感到困惑-应用程序,退出,集群。

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

EN

Stack Overflow用户

发布于 2018-01-03 22:24:52

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

ios::app (追加的缩写)意味着,所有的输出操作都是在文件的末尾完成的,而不是从一开始就覆盖文件。只有当文件也打开以供输出时,这才有意义。

ios::trunc (截断的缩写)意味着当文件被打开时,旧的内容会立即被删除。同样,只有当文件也打开以供输出时,这才有意义。

您的代码只使用默认的ios::out模式。因此,它从文件的开头开始写入,但不删除旧的内容。因此,新的内容将覆盖已经存在的内容--如果文件最初是10字节长,并且您编写了3个字节,结果将是您编写的3个字节,然后是原始内容的其余7个字节。更具体地说,如果文件最初包含:

代码语言:javascript
运行
复制
Firstname Lastname
30

然后编写FN LN,然后编写20 (每一行后面都有新行),结果文件如下所示:

代码语言:javascript
运行
复制
FN LN
20
 Lastname
30

因为您只覆盖文件的前9个字节(假设Unix样式的换行符)。

打开文件后,所有文件的输出都会按顺序顺序写入,除非使用outfile.seekp()转到不同的位置。对于您所写的每一件东西,它都不能追溯到文件的开头。如果使用seekp(),则不会产生任何效果;那么每次写入都会在文件的末尾进行。

票数 19
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48085781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档