c++中使用ofstream创建文本文件的问题
Problems with creating text files with ofstream in C++
我正在遵循一本c++教科书,目前在处理ofstream和ifstream的部分。我在同一个项目的main()函数中键入了几个例子(CodeBlocks 13.12)。
问题是开头的一些代码工作得很好,而其余的代码则不行。我试着在下面的代码后面解释它:
ofstream outfile("MyFile.dat");
if (!outfile)
{
cout << "Couldn’t open the file!" << endl;
}
outfile << "Hi" << endl;
outfile.close();
ofstream outfile2("MyFile.dat", ios_base::app);
outfile2 << "Hi again" << endl;
outfile2.close();
ifstream infile("MyFile.dat");
if (infile.fail())
{
cout << "Couldn't open the file!" << endl;
return 0;
}
infile.close();
ofstream outfile3("MyFile.dat", ios_base::app);
outfile3 << "Hey" << endl;
outfile3.close();
string word;
ifstream infile2("MyFile.dat");
infile2 >> word;
cout << word << endl; // "Hi" gets printed, I suppose it only prints 1st line ?
infile2.close();
ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
cout << endl << "The file already exists!" << endl;
return 0;
}
infile3.close();
ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl;
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?
ofstream outfile5("outfile5.txt");
outfile5 << "Lookit me! I’m in a file!" << endl;
int x = 200;
outfile5 << x << endl;
outfile5.close();
当代码执行时,唯一创建的文件是MyFile.dat,其内容是
Hi
Hi again
Hey
"Hi Foo"没有被写入文件,"outfile5.txt"没有被创建。
谁能给我解释一下为什么部分代码不能工作?以及如何纠正它,或者为了将来的参考需要注意什么?
In
ifstream infile3("MyFile.dat");
if (!infile3.fail())
{
cout << endl << "The file already exists!" << endl;
return 0;
}
你退出(return 0
)时,测试"MyFile.dat"
的成功打开。
ofstream outfile4("MyFile.dat");
outfile4 << "Hi Foo" << endl;
outfile4.close();
// this piece of code erases everything in MyFile.dat - why ?
"MyFile.dat"的内容正在被擦除,因为默认情况下您打开流以进行重写,而不是追加。如果要添加,请使用
outfile.open("MyFile.txt", std::ios_base::app);
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入