c++ - 如何清空文件中的一行并将其写回原来的位置?

标签 c++

我能够从文件中读取一个字符串,但是我在删除或清空该字符串时遇到了问题。 感谢您的帮助,祝您今天愉快。

#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <cstdlib>
#include <sstream>

using namespace std;

int main() {
    map<string, string> Data; // map of words and their frequencies
    string key;               // input buffer for words.
    fstream File;
    string description;
    string query;
    int count=0;
    int i=0;

    File.open("J://Customers.txt");

    while (!File.eof()) {
        getline(File,key,'\t');
        getline(File,description,'\n');
        Data[key] = description;
    }

    File.close();

    cout << endl;

    for ( count=0; count < 3; count++)  {
        cout << "Type in your search query.";
        cin >> query;
        string token[11]; 
        istringstream iss(Data[query]);  
        while ( getline(iss, token[i], '\t') ) {
            token[0] = query;
            cout << token[i] << endl;
            i++;        
        }  
    }   
    system("pause");

}//end main

最佳答案

基本上底层文件系统本身不支持。
所以你需要手动完成。

  • 以读取模式打开要修改的文件。
  • 以写入模式打开一个临时文件。
  • 从读取文件复制到写入文件。
    • 不要复制要删除的行。
  • 关闭两个文件
  • 交换文件系统中的文件
  • 删除旧文件。

查看您的代码:
你不应该这样做:

while (!File.eof())
{
     getline(File,key,'\t');
     getline(File,description,'\n');
     Data[key] = description;
}

文件中的最后一行不会正确设置 EOF,因此您将再次进入循环,但两次 getline() 调用将失败。

几个选项:

while (!File.eof())
{
     getline(File,key,'\t');
     getline(File,description,'\n');
     if(File) // Test to make sure both getline() calls worked
     {    Data[key] = description;
     }
}

// or more commonly put the gets in the condition

while (std::getline(File,line))
{
     key          = line.substr(0,line.find('\t'));
     description  = line.substr(line.find('\t')+1);
     Data[key]    = description;
}

关于c++ - 如何清空文件中的一行并将其写回原来的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1604487/

相关文章:

c++ - 模板化 ctor 上的编译器错误(这是编译器错误吗?)

c++ - 如何在前面定义的类 X 中的代码中使用后面定义的类 Y?

c++ - 如何终止从cin读取?

c++ - 未找到 libstdc++-6.dll

c++ - C动态成员结构

c++ - 通过重新排列其字母使回文字符串成为非回文字符串

java - 如何连接客户端(在 VirtualBox 上)和服务器(在本地主机上)?我使用 CORBA 和 C++/Java

c++ - 是否允许删除修改其参数?

c++ - 如何在 Qt 中转义 XML?

c++ - 捕获 OpenCV 后图像显示为绿色