如何在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)
相关文章:
- 在fstream期间忽略空行
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- fstream / ifstream / ofstream 对象如何转换为布尔值
- 使用命令的未定义引用<fstream>
- 如何检查文件是否已存在于 fstream C++中
- 如何正确使用 fstream 并在 char 数组中传递数据?
- 如何使用 fstream 的 .get 字符串?
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Windows std::fstream 修改文件后打开()?
- 如何删除文件中的数字,通过 c++ fstream 的
- std::fstream 在 MSVC 和 G++ 上使用 UTF-8 的不同行为
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 在istream_iterator中使用后的 C++ FSTREAM obj 回滚
- 如何使用单个fstream创建、读取和写入文件