替换.txt文件中的文本(C ++)

时间:2013-07-07 02:10:09

标签: c++ html

我的桌面上有多个.html文件,所有文件都链接在一起,但根据我自己的目录。这意味着如果这些文件放在不同的计算机上,链接将无法正常工作。我试图用C ++编写一个程序: 1)找到它所在的计算机的用户名。 (我已经走得那么远!) 2)用新用户名替换html文件中各个链接目录中的用户名。     我已经彻底研究过了,我找到了一个人替换某些字符串的方法。但是,当我尝试做同样的技巧时,它清除了整个文件。这是我的程序:

     #include <iostream>
     #include <Windows.h>
     #include <gl/GL.h>
     #include <gl/GLU.h>
     #include <windows.h>
     #include <WinBase.h>
     #include <string>
     #include <fstream>
     #include <algorithm>
     using namespace std;

     int main()
     {
         TCHAR name [ UNLEN + 1 ];
         DWORD size = UNLEN + 1;
         GetUserName( (TCHAR*)name, &size );

         string search_string = "Christian";
         string replace_string = "name";
         string inbuf;
         fstream input_file("kormain.txt", ios::in);
         ofstream output_file("kormain.txt");

         while (!input_file.eof())
         {
             getline(input_file, inbuf);

             int spot = inbuf.find(search_string);
             if(spot >= 0)
             {
                 string tmpstring = inbuf.substr(0,spot);
                 tmpstring += replace_string;
                 tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
                 inbuf = tmpstring;
             }

             output_file << inbuf << endl;
         }
         system ("PAUSE");
         return 0;
     }

1 个答案:

答案 0 :(得分:0)

您正在打开相同的文件进行读写,然后不检查状态。这可能会导致问题(取决于您的操作系统)。

作为快速测试,请更改您的output_file以写入其他文件名,看看您是否获得了预期的结果。