简体   繁体   English

C ++使用getline从文件中读取后,我无法再写入txt文件

[英]C++ After I use getline to read from a file I can no longer write to the txt file

I am able to write to a text file then I use getline and I can no longer write to the file. 我能够写一个文本文件,然后使用getline,而我不能再写该文件。

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

int main(){
 ifstream infile;
 fstream crypto;
 ofstream hacker;
 string tempString;
 string tempString2;
 string plaintext;
 string line;
 string dec;
.
.
.
crypto<<"hello";//write some stuff to file here
use getline(crypto, line, '\n')
crypto<<"hi";//Doesnt write to file anymore. 

Files have a single error status and a shared file-position indicator, which is used for both read and write operations. 文件具有单个错误状态和共享文件位置指示符,用于读取和写入操作。

If the error status is set, then neither read nor write operations will succeed on the file. 如果设置了错误状态,则对文件的读取和写入操作均不会成功。 Reading past the end of the file is one trigger that will cause the error status to be set, in this case until the file-position indicator is repositioned within the bounds of the file. 超过文件末尾的读取是一个触发器,它将导致设置错误状态,在这种情况下,直到文件位置指示器重新定位在文件的边界内为止。

As there is only a single position indicator for both reading and writing, you need to reposition that indicator each time you switch between reading and writing the same file to ensure that you are performing the next operation at the position where you intend it to occur. 由于只有一个位置指示器用于读取和写入,因此每次在读取和写入相同文件之间切换时都需要重新定位该指示器,以确保您在要发生的位置执行下一个操作。

从您的代码中很难看到原样(每行之后尝试返回),但我想您已将文件访问权限设置为“ read”。

The file has entered an error state. 该文件已进入错误状态。

Once the file is in an error state then all io operations will be ignored until you reset the error state. 一旦文件处于错误状态,则在重置错误状态之前,将忽略所有io操作。 So basically the above suggests that the getline operation failed in some way. 所以基本上上面表明getline操作在某种程度上失败了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM