访问/修改文本文件的特定行/列

时间:2015-08-17 23:57:25

标签: c++ string text edit fstream

我正在做一些练习,了解fstream是如何工作的,而且我已经碰壁了。

我初始化了一个3x3文本文件,每个元素都是'temp'

我希望能够访问特定的“元素”,将其删除,然后将其替换为字符串(可能大于或小于当前大小),但用制表符填充。

即。模拟文本文件的编辑

我一直在网上做一些研究,比如:http://www.cplusplus.com/doc/tutorial/files/但是我自己很难实现它。

因此文本文件“example.txt”包含:

temp    temp    temp    
temp    temp    temp    
temp    temp    temp    

我想打开它进行写作,寻找说法的位置,第2行,第2列(即对应于\ n和\ t字符),将其替换为另一个字符串,例如“thisisareplacement”

temp    temp    temp    
temp    thisisareplacement  temp    
temp    temp    temp    

根据我的理解,这可能是不可能的,因为我输入了更大的字符。但是我相信以某种方式定义这些\ n和\ t字符以包含我的字符串可以给我一个机会。

这是我的代码:

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

    int main () {

    int numRows = 3;

      ofstream myfile ("example.txt");
      if (myfile.is_open())
      {
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < numRows; j++) {
            myfile << "temp\t";
            } 
        myfile << "\n";
        }

        myfile.close();
      }

      else { cout << "Unable to open file"; }

    // now i want to try and edit a specific row (\n) and column (\t)


      return 0;
    }

0 个答案:

没有答案