如何在fstream中编写

How to write in fstream?

本文关键字:fstream      更新时间:2023-10-16

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

#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并尝试写入该文件,我得到的错误信息:

智能感知:没有操作符"<<"匹配这些操作数操作数类型为:std::ifstream

我想问我怎么能写到那个文件,我问,因为如果我使用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",基本上意味着"获取输入失败"),它将不填充行,并且您的代码将不知道。

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

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

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