【问题标题】:How to write in fstream?如何在 fstream 中写入?
【发布时间】:2014-06-02 14:28:39
【问题描述】:

以下文件打印文件的第二行:

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

int main () 
{
// Open your file
ifstream someStream( "textFile.txt" );

// Set up a place to store our data read from the file
string line;

// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );

// Now begin your useful code
while( !someStream.eof() ) {
    // This will just over write the first line read
    getline( someStream, line );
    cout << line << endl;
}

return 0;
}

我想问我如何写入该文件,我问是因为如果我使用

ofstream 而不是ifstream 我不能使用getline 函数,如果我使用ofstream 我不能写入那个文件。

如果我使用ifstream 并尝试写入该文件,我会收到错误消息:

IntelliSense:没有运算符“

【问题讨论】:

  • 分两个单独的步骤进行,一个是使用ifstream 读取所有输入,然后关闭另一个ofstream 以写入此文件。
  • 相关,在循环中检查 eof 很可能不是您想要的 (Why is iostream::eof inside a loop condition considered wrong?)。您应该将整个 getline 调用作为 while 条件。

标签: c++ file ifstream getline ofstream


【解决方案1】:

我想问我如何写入那个文件,我问是因为如果我使用 ofstream 而不是 ifstream 我不能使用 getline 函数,如果我使用 ofstream 我不能写入那个文件

std::getline 是为 std::istream 制作的,它是专门化的(你将无法使用 getline 来写东西)。

要写入文件:

ifstream someStream( "textFile.txt" );
// your code here (I won't repeat it)

someStream.close(); // flush and close the stream
ofstream output("textFile.txt", std::ios::ate|std::ios::app); // append at end of file
output << "this string is appended at end of the file";
std::string interestingData{ "this is not a fish" };
output << interestingData; // place interesting data in the file

在使用 i/o 流时应牢记的其他一些事项:

// Set up a place to store our data read from the file
string line;

// Read and throw away the first line simply by doing
// nothing with it and reading again
getline( someStream, line );

这不好:如果文件不存在或不包含正确的数据类型,或者你没有读取权限等等,getline 会将someStream 设置为无效状态(不同于"eof "这基本上意味着"获取输入失败"),它不会填写该行,并且您的代码不会知道这一点。

逐行读取文件的正确代码可以在here找到。

要在写入文件之前重置文件,请确保在打开文件时使用正确的状态标志:

ofstream someStream( "textFile.txt", std::ios::trunc );
someStream.close(); // flush and reset the file, with no content added (= make empty)

【讨论】:

  • 我想在写入文件之前,文件应该是空的。请告诉如何做到这一点,
  • 要清理文件,打开文件进行写入,不附加标志,然后关闭它(我将编辑帖子)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2015-12-02
  • 2018-09-04
  • 2020-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多