⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 operatefile.cpp

📁 一个ADO小程序
💻 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 + -