20
2012
05

C++/c#修改hosts文件

c++

#include<iostream>
#include<fstream>
#include <WTypes.h>
#include <Winbase.h>
using namespace std;
int main()
{
ofstream outf;
char * lpFileName="C:\\Windows\\System32\\drivers\\etc\\hosts";
DWORD  dwAttribute   ::GetFileAttributes(lpFileName);
if(dwAttribute   FILE_ATTRIBUTE_READONLY)
{
dwAttribute  &=  ~FILE_ATTRIBUTE_READONLY;
SetFileAttributes(lpFileName,dwAttribute);
}
outf.open("C:\\Windows\\System32\\drivers\\etc\\hosts" , ifstream::in);//要覆盖文件,把最后一个参数去掉
outf<<"\n# Copyright (c) 1993-1999 Microsoft Corp.";
outf<<"\n#";
outf<<"\n# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.";
outf<<"\n#";
outf<<"\n# This file contains the mappings of IP addresses to host names. Each";
outf<<"\n# entry should be kept on an individual line. The IP address should";
outf<<"\n# be placed in the first column followed by the corresponding host name.";
outf<<"\n# The IP address and the host name should be separated by at least one";
outf<<"\n# space.";
outf<<"\n#";
outf<<"\n# Additionally, comments (such as these) may be inserted on individual";
outf<<"\n# lines or following the machine name denoted by a '#' symbol.";
outf<<"\n#";
outf<<"\n# For example:";
outf<<"\n#";
outf<<"\n# 102.54.94.97 rhino.acme.com # source server";
outf<<"\n# 38.25.63.10 x.acme.com # x client host";
outf<<"\n127.0.0.1 localhost";
outf<<"\n";
outf.close();
return 0;
}

 c#

//using System.IO;
string fpath = @"C:\WINDOWS\system32\drivers\etc\hosts";
File.SetAttributes(@fpath, FileAttributes.Normal);
FileStream fs = new FileStream(@fpath, FileMode.Append); //写入的方式可改变,这里是追加
StreamWriter sw = new StreamWriter(fs);

//写入的一行内容
sw.WriteLine("127.0.0.1     www.tt.com");

//写入大量内容前面加 &ldquo;@&rdquo;符号
sw.WriteLine(@"0.0.0.0 www.bfaft.com
0.0.0.0 bbs.bfaft.com
0.0.0.0 bfaft.com
");
sw.Close();
fs.Close();

 

 



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。