?? operatefile.cpp
字號:
// OperateFile.cpp : Defines the entry point for the console application.
//
#include "StdAfx.h"
#include <wtypes.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#ifdef WIN32
#define TEST_FILE_READ "F:\\FileForRead.txt"
#define TEST_FILE_WRITE "F:\\FileForWrite.txt"
#else
#define TEST_FILE_READ "F:\FileForRead.txt"
#define TEST_FILE_WRITE "F:\FileForWrite.txt"
#endif
const WORD BufferLen = 1024;
const int BufferLenFile = 1024*1024;
void get()
{
ifstream ifs(TEST_FILE_READ);
while (ifs.good())
{
char ch = '\0';
ifs.get(ch);
if ( ch == 'h')
{
ch = 'H';
}
cout << ch;
}
ifs.close();
}
void getline()
{
ifstream ifs(TEST_FILE_READ);
ofstream ofsWrite(TEST_FILE_WRITE); //獲得用來寫入的文件的句柄
while (ifs.good())
{
char buf[BufferLen] = "\0";
ifs.getline(buf, sizeof(buf),'\n');
//ifs.getline(buf, sizeof(buf),EOF); //相當于全文讀取
if (ofsWrite.good())
{
ofsWrite << buf << "\n";
}
cout << buf << endl;
}
ifs.close();
ofsWrite.close();
}
// 找出 {set password = "ams1000" ;# 此處演示找到指定位置并修改} 這一行,并將密碼替換掉
void Replace( string NewPwd )
{
char buf[BufferLen] = "\0";
string OldPwd = "\0"; //記錄原密碼
string WholeFileString = "\0"; // 保存整個緩沖,供操作完后重新寫入
string StrLine; // 保存讀出的每一行
string StrFind = "set password = \""; //通過此字符串確定密碼在此行描述
short npos = -1; //判斷是否找到了記錄密碼的行 npos != -1 說明已經找到
WORD npos1 = StrFind.length(); //發現第一個引號的位置
WORD npos2 = 0; //發現第二個引號的位置
const WORD pos = 0; //表示從每一行的開始處開始查詢
ifstream ifs(TEST_FILE_READ);
while (ifs.good())
{
ifs.getline(buf,sizeof(buf),'\n');
StrLine = buf;
npos = StrLine.find(StrFind,pos);
if ( npos != -1)
{
int npos2 = StrLine.find("\"",npos1);
OldPwd.append(StrLine,npos1-1,npos2-npos1+2);
cout << "Old Password is " << OldPwd << endl;
//cout << "npos1 = " << npos1 << endl;
//cout << "npos2 = " << npos2 << endl;
StrLine.replace(npos1,npos2-npos1,NewPwd);
}
cout << StrLine <<endl;
WholeFileString.append(StrLine);
if (ifs.good())
{
WholeFileString.append("\n");
}
}
ifs.close();
//此處應該有更加好的辦法,沒必要關閉掉再打開然后重新寫入
ofstream ofs(TEST_FILE_READ);
if ( ofs.good() )
{
ofs << WholeFileString;
}
ofs.close();
}
void GetWholeFile()
{
/*
char buf[BufferLen];
ifstream ifs(TEST_FILE_READ);
//read(unsigned char *buf,int num);
ifs.read(buf,BufferLenFile);
cout << buf ;
*/
//cout << word << endl;
string word;
ifstream ifs(TEST_FILE_READ);
if ( ifs.good())
{
ifs >> word; // 為什么這里只讀到第一個空格為止,用 ">>" 怎樣才能全部讀出來
}
ifs.close();
}
int main(int argc, char* argv[])
{
//get();
//getline();
//GetWholeFile();
Replace( "NewPassword" );
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -