2013-07-07 138 views
0

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

 #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; 
    } 
+0

适当的解决方案将是相对URI的。这种方式甚至可以在网站上运行 – MSalters

回答

0

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

作为一个快速测试,改变你的output_file写入到一个不同的文件名,看看你是否得到预期的结果。

+0

谢谢!我猜这只是与unicode不兼容? – user2557334

+0

不,不会与unicode有任何关系。根据操作系统的不同,打开写入操作可能会失败,因为您已经打开阅读。或者它可能有用,但一旦你写入它,读取开始出现问题。另一个“修复”是在打开文件后检查状态。 – John3136