【发布时间】:2021-10-18 18:42:38
【问题描述】:
请先看这段代码,然后我会问我的问题。
#include <bits/stdc++.h>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
int main() {
std::ofstream out_file ("outfile.txt"); /* creates a outfile.txt */
if (!out_file) { // checks files existence
std::cerr << "Error bruh!" << endl;
return (1);
}
int num = 100;
double total = 456.78;
std::string name = "atik";
out_file << num << "\n" // writing to the file
<< total << "\n"
<< name << endl;
/* Reading from file, because i want to! - */
std::ifstream in_file("outfile.txt"); // will open outfile for reading.
char c;
while (in_file.get(c)) {
cout << c;
}
/*
Output (as expected) -
100
456.78
atik
Right Now My **output.txt** file is - (as expected)
100
456.78
atik
*/
/* Appending the file that we just created - */
std::ofstream out_file2 ("outfile.txt", std::ios::app);
cout << "\nEnter something to write in file : " << endl;
std::string line;
getline(cin, line);
out_file2 << line; // writes to out_file2
/* Reading from file again - */
std::ifstream in_file2("outfile.txt"); // will open outfile.txt for reading.
if( !in_file2 ) {
std::cerr << "File didn't open. Error encountered." << endl;
}
char ch;
cout << endl;
while( in_file2.get(ch) ) {
cout << ch;
}
/*
Output (unexpected? why?)-
100
456.78
atik
*/
in_file.close();
in_file.close();
out_file.close();
out_file2.close();
return 0;
}
现在,我的outfile..txt 是-(如预期的那样):
100
456.78
atik
Hello there
那么为什么in_file2 的输出没有显示Hello there?为什么它会截断Hello there?谁能解释一下?
【问题讨论】:
-
这只是一个大程序吗?在这种情况下,您需要关闭(或至少刷新)ofstreams,然后才能对写入文件做出任何保证。
-
我必须在哪一行刷新ofstream?如果您告诉我最好的(语法)方法,那将非常有帮助。谢谢
-
该死的@frank 非常感谢。因为有你,我今天可以安然入睡。我的问题已经解决,但我的疑问仍然存在。为什么我们需要在将行写入 out_file2 之后刷新流?
-
@LearningNoob123:见my answer。问题在于用户模式缓冲区。
-
@LearningNoob123,因为您没有写入文件,所以您正在向负责写入文件的对象发送数据,并且它会在它喜欢的时候(或者当你强迫它这样做时)这样做。
标签: c++ c++11 file-handling