我知道默认的文件打开模式是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;
然后我对文件的三种开放模式感到困惑-应用程序,退出,集群。
如果我输入“Zara”和年龄“9”,输出应该是“9ara”。然而,事实并非如此。是“Zara 9”。
发布于 2018-01-03 22:24:52
ios::out
是std::ofstream
的默认模式,它意味着可以使用输出操作(即可以写入文件)。
ios::app
(追加的缩写)意味着,所有的输出操作都是在文件的末尾完成的,而不是从一开始就覆盖文件。只有当文件也打开以供输出时,这才有意义。
ios::trunc
(截断的缩写)意味着当文件被打开时,旧的内容会立即被删除。同样,只有当文件也打开以供输出时,这才有意义。
您的代码只使用默认的ios::out
模式。因此,它从文件的开头开始写入,但不删除旧的内容。因此,新的内容将覆盖已经存在的内容--如果文件最初是10字节长,并且您编写了3个字节,结果将是您编写的3个字节,然后是原始内容的其余7个字节。更具体地说,如果文件最初包含:
Firstname Lastname
30
然后编写FN LN
,然后编写20
(每一行后面都有新行),结果文件如下所示:
FN LN
20
Lastname
30
因为您只覆盖文件的前9个字节(假设Unix样式的换行符)。
打开文件后,所有文件的输出都会按顺序顺序写入,除非使用outfile.seekp()
转到不同的位置。对于您所写的每一件东西,它都不能追溯到文件的开头。如果使用seekp()
,则不会产生任何效果;那么每次写入都会在文件的末尾进行。
https://stackoverflow.com/questions/48085781
复制相似问题