Skip to content
MPGHThe Dark Arts
/
RegisterLog in
Forum
Community
What's NewLatest posts across the boardTrendingHottest threads right nowSubscribedThreads you follow
Discussion
GeneralIntroductionsEntertainmentDebate FortFlaming & Rage
Board
News & AnnouncementsMPGH TimesSuggestions & HelpGiveaways
More Sections
Art & Graphic DesignProgrammingHackingCryptocurrency
Hacks & Cheats
Games
ValorantCS2 / CS:GOCall of Duty / WarzoneFortniteApex LegendsEscape From Tarkov
+14 moreLeague of LegendsGTA VMinecraftRustROTMGBattlefieldTroveBattleOnCombat ArmsCrossFireBlackshotRuneScapeDayZDead by Daylight
Resources
Game Hacking TutorialsReverse EngineeringGeneral Game HackingAnti-CheatConsole Game Hacking
Tools
Game Hacking ToolsTrainers & CheatsHack/Release NewsNew
Submit a release →Share your cheat, tool, or config with the community.
AINEW
AI Tools
General & DiscussionPrompt EngineeringLLM JailbreaksHotAI Agents & AutomationLocal / Open Models
AI × Gaming
AI Aimbots & VisionML Anti-CheatGame Bots & Automation
Create
AI Coding / Vibe CodingAI Art & MediaAI Voice & TTS
The AI frontier →Where game hacking meets modern machine learning. Jump in.
Marketplace
Buy & Sell
SellingBuyingTradingUser Services
Trust & Safety
Middleman LoungeMarketplace TalkVouch Copy Profiles
Money
Cryptocurrency TalkCurrency ExchangeWork & Job Offers
Start selling →List accounts, services, and goods. Use the middleman to trade safe.
MPGH The Dark Arts

A community for offensive security research, reverse engineering, and AI.

Community

ForumMarketplaceSearch

Account

RegisterLog in

Legal

Privacy PolicyForum RulesHelp & FAQ
© 2026 MPGH · All rights reserved.Built by the community, for the community. For educational purposes onlyContent is shared for security research and education — we don't condone illegal use. You're responsible for complying with applicable laws. Use at your own risk.
Home › Forum › Programming › C++/C Programming › C, C++ and VC++ Snippets

C, C++ and VC++ Snippets

Posts 1–15 of 57 · Page 1 of 4
NextGen1
NextGen1
C, C++ and VC++ Snippets
Use this format for submitting snippets

It may be used later to parse the snippets to a application (like the one in the VB Section)

If you're going to post a snippet in this thread then you should be posting it in the following format:

Snippet Name: ____________________
Keywords: ____,____,____ ...
Description(Optional): _______________________
Code:
Code:
Your Code Here...
This is to be used for any small bit of code you would like to share.


#1 · 15y ago
Auxilium
Auxilium
First to post snippet

Name:Auto space presser can be used for Bunny Hopper (doesnt work on CA) dont know about other games.

Keywords:Bunny ,hop, hopper, kallisti, is, cool

description:Simulates space press to jump

[highlight=cpp]
//dont post on this thread telling me how
//i couldve used something other than goto plox
//ng gonna rageban you too
start: //haters gonna hate
while(true)
{
Sleep(200);
if(GetAsyncKeyState(VK_F8))
{
while(true)
{
Sleep(600);
keybd_event(VK_SPACE,0x20,KEYEVENTF_EXTENDEDKEY | 0,0);
if(GetAsyncKeyState(VK_ESCAPE))
{
goto start; //start hating
}

if(GetAsyncKeyState(VK_F9))
{
MessageBox(NULL,L"Bye",L"",MB_ICONEXCLAMATION);
return 0;
}
}
}[/highlight]
#2 · edited 15y ago · 15y ago
Void
Void
First is the worst Patrick, second is the best. ftw.

Snippet name: Low level keyboard hook.

Keywords: Low,Level,Keyboard,Hook,SetWindowsHookEx,Hotkeys

Description: Settings up a low level keyboard hook using SetWindowsHookEx for hotkey use.

Code:
[highlight=cpp]
#include <windows.h>
#include <iostream>

using namespace std;

HHOOK keybdhook;
LRESULT CALLBACK KeyboardHook(int nCode,WPARAM wParam,LPARAM lParam); // declaration of the callback

int main()
{
keybdhook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardHook,GetMo duleHandle(0),0);
if(keybdhook == 0)
{
cout <<"Fail to create hook"<<endl;
}

MSG msg;
while(GetMessage(&msg,0,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

}

LRESULT CALLBACK KeyboardHook(int nCode,WPARAM wParam,LPARAM lParam)
{
KBDLLHOOKSTRUCT* key;
if(wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)
{
key = (KBDLLHOOKSTRUCT*)lParam;

//hotkey example
if(key->vkCode == VkKeyScan('a'))
{
cout << "You pressed 'a'" << endl;
}
if(key->vkCode == VK_F1)
{
cout <<"You pressed the F1 key"<<endl;
}
}
return CallNextHookEx(keybdhook,nCode,wParam,lParam);
}
[/highlight]
#3 · edited 15y ago · 15y ago
Kallisti
Kallisti
3rd is the one with the dang treasure chest.

Name: Record mouse coordinates
keywords: patty, patrick, patty c, is, a, badass
description: title

[highlight=cpp]while(true)
{
POINT mousePos;
GetCursorPos(&mousePos);
cout << "(" << mousePos.x << "," << mousePos.y << ")";
Sleep(20);
system("cls");
}[/highlight]
#4 · edited 15y ago · 15y ago
freedompeace
freedompeace
Snippet Name: SMTP example.
Keywords: email, POP, POP3, SMTP, emails, electronic, mail, messages, C++, C
Description(Optional): Demonstration of how to use SMTP to send emails

[highlight=cpp]
#include<iostream>
#include <syspes.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
using namespace std;
#define HELO "HELO 192.168.1.1\r\n"
#define DATA "DATA\r\n"
#define QUIT "QUIT\r\n"

//#define h_addr h_addr_list[0]
//FILE *fin;
int sock;
struct sockaddr_in server;
struct hostent *hp, *gethostbyname();
char buf[BUFSIZ+1];
int len;
char *host_id="192.168.1.10";
char *from_id="username@Domain.com";
char *to_id="username@Domain.com";
char *sub="testmail\r\n";
char wkstr[100]="hello how r u\r\n";

/*=====Send a string to the socket=====*/

void send_socket(char *s)
{
write(sock,s,strlen(s));
write(1,s,strlen(s));
//printf("Client:%s\n",s);
}

//=====Read a string from the socket=====*/

void read_socket()
{
len = read(sock,buf,BUFSIZ);
write(1,buf,len);
//printf("Server:%s\n",buf);
}

/*=====MAIN=====*/
int main(int argc, char* argv[])
{

/*=====Create Socket=====*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock==-1)
{
perror("opening stream socket");
exit(1);
}
else
cout << "socket created\n";
/*=====Verify host=====*/
server.sin_family = AF_INET;
hp = gethostbyname(host_id);
if (hp==(struct hostent *) 0)
{
fprintf(stderr, "%s: unknown host\n", host_id);
exit(2);
}

/*=====Connect to port 25 on remote host=====*/
memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);
server.sin_port=htons(25); /* SMTP PORT */
if (connect(sock, (struct sockaddr *) &server, sizeof server)==-1)
{
perror("connecting stream socket");
exit(1);
}
else
cout << "Connected\n";
/*=====Write some data then read some =====*/
read_socket(); /* SMTP Server logon string */
send_socket(HELO); /* introduce ourselves */
read_socket(); /*Read reply */
send_socket("MAIL FROM: ");
send_socket(from_id);
send_socket("\r\n");
read_socket(); /* Sender OK */
send_socket("VRFY ");
send_socket(from_id);
send_socket("\r\n");
read_socket(); // Sender OK */
send_socket("RCPT TO: "); /*Mail to*/
send_socket(to_id);
send_socket("\r\n");
read_socket(); // Recipient OK*/
send_socket(DATA);// body to follow*/
send_socket("Subject: ");
send_socket(sub);
read_socket(); // Recipient OK*/
send_socket(wkstr);
send_socket(".\r\n");
read_socket();
send_socket(QUIT); /* quit */
read_socket(); // log off */

//=====Close socket and finish=====*/
close(sock);
exit(0);
[/highlight]
#5 · edited 15y ago · 15y ago
Jason
Jason
Quote Originally Posted by Kallisti View Post
Don't get this too offtopic.
Okay here's a snippet (don't even know if it works in C++, I hope it does.)

[highlight=cpp]
int main()
{
while(true)
{
for(int i=0; i<256; i++)
{
if(GetAsyncKeyState(i)&1)
{
cout<<"I don't know how to convert from keyvalue to string, yay!";
}
}
}

}
[/highlight]
#6 · edited 15y ago · 15y ago
Kallisti
Kallisti
Auto Refresher
Kallisti is cool
Auto refreshes
[highlight=cpp]
#include <windows.h>
#include <iostream>
using namespace std;
DWORD timesPressed = 0;


int main()
{

while(true)
{
startLoop:
Sleep(100);
if(GetAsyncKeyState(VK_NUMPAD0))
{
while(true)
{
if(GetAsyncKeyState(VK_END))
{
cout << "Stopped. Press 'Numpad 0' to start again.\n";
goto startLoop;
}
Sleep(12500);
timesPressed++;
keybd_event(VK_F5,0x74,KEYEVENTF_EXTENDEDKEY | 0,0);
cout << "Times pressed: " << timesPressed << '\n';
}
}
}
}
[/highlight]
#7 · edited 15y ago · 15y ago
.::SCHiM::.
.::SCHiM::.
Snippet Name: Convert strings to integers
Keywords: String, Integer, Loops
Description(Optional): A messy bit of code used by me to convert strings to integers


Code:
#include <math.h>
#include <string.h>
Code:
unsigned long StrToInt(std::string str){
unsigned long rint = NULL;
unsigned long size = str.size();
unsigned long fi[sizeof(str)];
unsigned long mul;

for( int i = 0; i != size; i++){
        if( str.at(i) == '0' ) fi[i] = 0;
	if( str.at(i) == '1' ) fi[i] = 1;
	if( str.at(i) == '2' ) fi[i] = 2;
	if( str.at(i) == '3' ) fi[i] = 3;
	if( str.at(i) == '4' ) fi[i] = 4;
	if( str.at(i) == '5' ) fi[i] = 5;
	if( str.at(i) == '6' ) fi[i] = 6;
	if( str.at(i) == '7' ) fi[i] = 7;
	if( str.at(i) == '8' ) fi[i] = 8;
	if( str.at(i) == '9' ) fi[i] = 9;
}

for(int i = 0; i != str.size() ; i++){
	mul = (1 * pow(10, (double)size-1));
	size--;
	rint += ( mul * fi[i]);
}
return rint;
}
Use

Code:
int i = (int) StrToInt("5192491");
i wil now hold 5192491, as an integer variable

-SCHiM


Hell: Or you just use atoi(str.c_str());
#8 · edited 15y ago · 15y ago
FA
fateinabox
Your code to convert alpha to numeric is a little larger than it needs to be..Atoi isn't always a reliable routine to use so a smaller alternative could be to use

Snippet: Smaller Alpha To Numeric ( atoi )
Keywords: String, Numeric, Alpha, ATOI, ITOA

[php]
#define isnumeric(a) ( ( a >='0' && a <='9' ) )
#define isalpha(a) !isnumeric(a)
#define tonum(a) ( ( a - '0' ) )

long strtonum( char *buffer )
{
long tmpNum;
tmpNum = 0;

if ( !isnumeric(*buffer) ) return -1;

while ( isnumeric(*buffer) )
{
tmpNum = ( tmpNum * 10 ) + tonum( *buffer );
(buffer)++;
}
return tmpNum;
}
[/php]

Usage: retval = strtonum( "1234" )
retval=1234
#9 · edited 15y ago · 15y ago
RA
Rave_
Snippet Name: Calculator ASCII
Description(Optional): This was a project of mine and it's been a while. It will act like a calculator but in ascii.

Code:
Code:
#include "stdafx.h"
#include "windows.h"
#include <iostream>
#include <cmath>

using namespace std;

struct Define
{
	int option;
	char operators;
	long basica;
	long basicb;
	float adva;
	long answerbasic;
	float answeradv;
};

Define df;

namespace Calculator
{
	int MainLobby( )
	{
		printf( " \nWelcome to Calculator(ASCII)!\n");
		printf( " Enter: ");
		printf( " '1' for Basic. ");
		printf( " '2' for Advanced : ");
		cin >> df.option;
		return 0;
	}

	int BasicLobby( )
	{
		cout << " Enter operator ( +, -, *, / ): ";
		cin >> df.operators;
		cout << " Enter a number: ";
		cin >> df.basica;
		cout << " Enter another number: ";
		cin >> df.basicb;

		if ( df.operators == ('+') )
		{
			df.answerbasic = df.basica + df.basicb;
			cout << df.basica << " " << df.operators << " " << df.basicb << " = " << df.answerbasic;
		}
		
		if ( df.operators == ('-') )
		{
			df.answerbasic = df.basica - df.basicb;
			cout << df.basica << " " << df.operators << " " << df.basicb << " = " << df.answerbasic;
		}

		if ( df.operators == ('*') )
		{
			df.answerbasic = df.basica * df.basicb;
			cout << df.basica << " " << df.operators << " " << df.basicb << " = " << df.answerbasic;
		}

		if ( df.operators == ('/') )
		{
			df.answerbasic = df.basica / df.basicb;
			cout << df.basica << " " << df.operators << " " << df.basicb << " = " << df.answerbasic;
		}

		cout << "\n\n";

		return 0;
	}

	int AdvancedLobby( )
	{
		cout << "Enter operators 's' for square root: ";
		cin >> df.operators;
		cout << "Enter a number: ";
		cin >> df.adva;

		if ( df.operators == ('s') )
		{
			df.answeradv = sqrt(df.adva);
			cout << " square root " << df.adva << " = " << df.answeradv;
		}

		cout << "\n\n";

		return 0;

	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	while( 1 )
	{
Restart:
		Calculator::MainLobby( );
		switch(df.option)
		{
		case (1): Calculator::BasicLobby( ); break;
		case (2): Calculator::AdvancedLobby( ); break;
		default: cout << "\nPlease enter 1 or 2."; break;
		}
		goto Restart;
	}

	return 0;
}
#10 · 15y ago
master131
[MPGH]master131
Snippet Name: Simple Keylogger/GAKS Tool
Keywords: keylogger, GetAsyncKeyState, keyboard, master131.

Code:
//GAKS.cpp written by master131

#include <Windows.h>
#include <iostream>

int main()
{
	using namespace std;
	char* keys[] = {"{LEFTMOUSE}", "{RIGHTMOUSE}", "{CANCEL}", 
		"{MIDDLEMOUSE}", "{XBUTTON1}", "{XBUTTON2}", "", "{BACKSPACE}", "{TAB}",
		"","","{CLEAR}", "{ENTER}", "", "", "{SHIFT}", "{CTRL}", "{ALT}", "{PAUSE}", "{CAPSLOCK}" };
	char* otherkeys[] = {"{SPACE}", "{PGUP}", "{PGDOWN}", "{END}", "{HOME}", "{LEFT ARROW}", "{UP ARROW}", 
		"{RIGHT ARROW}", "{DOWN ARROW}", "{SELECT}", "{PRINT}", "{EXECUTE}", "{PRNTSCREEN}", "{INS}",
		"{DEL}", "{HELP}"};
	char* standardkeys[] = {":", "+", ",", "-", ".", "/", "`"};
	char* misckeys[] = {"[", "\\", "]", "'"};
	char* numpadkeys[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "+", "", "-", ".", "/"};

	while(1)
	{
		for(int i = 0; i < 255; i++)
			if(GetAsyncKeyState(i))
			{
				while(GetAsyncKeyState(i)) { };
				if(i >= 1 && i <= 19) //Special Keys
					cout << keys[i-1];
				if(i >= 32 && i <= 47) //Other keys
					cout << otherkeys[i-32];
				if(i >= 48 && i <= 90) //Literal Keys
					cout << (char)tolower(i);
				if(i >= 96 && i <= 111) //Numpad keys
					cout << numpadkeys[i-96];
				if(i >= 112 && i <= 135) //F keys
					cout << "{F" << i - 111 << "}";
				if(i >= 186 && i <= 192) //Punctuation Keys
					cout << standardkeys[i-186];
				if(i >= 219 && i <= 222) //Misc keys
					cout << misckeys[i-219];
			}
		Sleep(1);
	}
	return 0;
}

Hell: Or use a WH_KEYBOARD hook =3
#11 · edited 15y ago · 15y ago
WH
whit
PC NAME & Draw Battery Life
I Orginally Posted these in a Thread but Threads Die So Here Ya Go

Draw PC NAME:
Code:
char  pcName [MAX_COMPUTERNAME_LENGTH + 1];
DWORD dwPcName = sizeof ( pcName );   

if ( GetComputerName (pcName,&dwPcName)) cFont->DrawText(300,300,Green,pcName,D3DFONT_SHADOW);
Draw Battery Life:
Code:
void Drawbatterylife( int x, int y )
{
   SYSTEM_POWER_STATUS status;
   GetSystemPowerStatus( &status );

   int life = status.BatteryLifePercent;
   char szLife[256];

   sprintf(szLife,"%i",life);
   DrawString(x, y, White, m_font, szLife);

   switch (status.BatteryFlag) {
              case 1: 
		 DrawString( x, y + 17, White, m_font, "High");
		 break;

	      case 2: 
	          DrawString( x, y + 17, White, m_font, "Low");
	          break;

               case 4: 
	          DrawString( x, y + 17, White, m_font, "Criticial");
                  break;

	       case 128: 
		  DrawString( x, y + 17, White, m_font, "No system battery");
		  break;

               case 256: 
                  DrawString( x, y + 17, White, m_font, "Unknown status");
                  break;

	}
}
#12 · 15y ago
Clarkie
Clarkie
Snippet Name: Clarkie's Detours
Keywords: Detour, Hook, Hack, Source
Description(Optional): Thank Topblast ^^
Code:
[highlight=c++]#pragma pack(push)
#pragma pack(1)

typedef struct {
unsigned char bNop;
unsigned char bPush;
unsigned long dwAddress;
unsigned char bRet;
} TestJmp;


typedef struct {
TestJmp bOPS;
unsigned char bNop;
unsigned char bJmp;
unsigned long dwAddress;
} Tjmp;
#pragma pack(pop)

bool Hook(PBYTE pTargetAddr, PBYTE pNewAddr, VOID** pCallOrigAddress)
{
TestJmp recJump;
Tjmp RetJump;
DWORD dwProtect;
*pCallOrigAddress = VirtualAlloc(0, sizeof(Tjmp), (MEM_COMMIT | MEM_RESERVE), PAGE_EXECUTE_READWRITE);
if( pCallOrigAddress != NULL)
{
WriteNOP(&RetJump, sizeof(Tjmp));

memcpy(&RetJump.bOPS, pTargetAddr, sizeof(TestJmp));
RetJump.bNop = 0x90;
RetJump.bJmp = 0xE9;
RetJump.dwAddress = (DWORD(pTargetAddr) + (sizeof(TestJmp)+1))-DWORD(*pCallOrigAddress)-(((sizeof(TestJmp)*2)));
memcpy(*pCallOrigAddress, &RetJump, sizeof(Tjmp));

if( WriteNOP(pTargetAddr, (sizeof(TestJmp))) == true &&
VirtualProtect(pTargetAddr, sizeof(TestJmp), PAGE_EXECUTE_READWRITE, &dwProtect) == TRUE)
{
WriteNOP(&recJump, sizeof(TestJmp));
recJump.bNop = 0x90;
recJump.bPush = 0x68;
recJump.dwAddress = DWORD(pNewAddr);
recJump.bRet = 0xC3;
memcpy(pTargetAddr, &recJump, sizeof(TestJmp));
VirtualProtect(pTargetAddr, sizeof(TestJmp), dwProtect, &dwProtect);
return true;
}
}
return false;
}
[/highlight]
#13 · 15y ago
Cyberdyne
Cyberdyne
Okay, I'm bored. and I was reading a VC++ book

Snippet Name: Calculate Gas Mileage
Keywords: Arrays

Code:

Code:
// Calculating gas mileage
#include <iostream>
#include <iomanip>

using std::cin;
using std::cout;
using std::endl;
using std::setw;
using namespace std;

int main()
{
   const int MAX(20);                      // Maximum number of values
   double gas[ MAX ];                      // Gas quantity in gallons
   long miles[ MAX ];                      // Odometer readings
   int count(0);                           // Loop counter
   char indicator('y');                    // Input indicator

   while( ('y' == indicator || 'Y' == indicator) && count < MAX )
   {
      cout << endl << "Enter gas quantity: ";
      cin >> gas[count];                   // Read gas quantity
      cout << "Enter odometer reading: ";
      cin >> miles[count];                 // Read odometer value

      ++count;
      cout << "Do you want to enter another(y or n)? ";
      cin >> indicator;
   }

   if(count <= 1)                     // count = 1 after 1 entry completed
   {                                  // ... we need at least 2
      cout << endl << "Sorry - at least two readings are necessary.";
      cin.get();
      return 0;
   }

   // Output results from 2nd entry to last entry
   for(int i = 1; i < count; i++)
   {
     cout << endl
          << setw(2) << i << "."             // Output sequence number
          << "Gas purchased = " << gas[i] << " gallons" // Output gas
          << " resulted in "                 // Output miles per gallon
          << (miles[i] - miles[i - 1])/gas[i] << " miles per gallon.";
   }

   cout << endl;
   system("PAUSE");
   return 0;
}
#14 · 15y ago
Hassan
Hassan
Snippet Name: File Handling
Keywords: Fuck,Assignments

Code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <conio.h>
using namespace std;
void ReRun();
bool CopyF(char *SourceFile,char *DestinationFile);
void main()
{
	system("cls");
	cout << "Enter 'r' to read contents of an existing file." << endl;
	cout << "Enter 'w' to write contents to a new file." << endl;
	cout << "Enter 'a' to append contents of an existing file." << endl;
	cout << "Enter 'c' to copy a file to another place." << endl;
	cout << "Enter 'm' to move a file to another place." << endl;
	cout << "Enter 'd' to delete an existing file." << endl << endl;
	cout << "Enter your choice: ";
	char choice;
	cin >> choice;
	switch(choice)
	{
	case 'r':
	case 'R':
		{
			cin.ignore();
			char FileName[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the filename you want to read data from: ";
			cin.getline(FileName,FILENAME_MAX);
			fstream ReadonlyFile;
			ReadonlyFile.open(FileName,ios::in);
			if(ReadonlyFile.is_open())
			{
				while(!ReadonlyFile.eof())
				{
					string CurrentLine;
					cout << endl;
					while(getline(ReadonlyFile,CurrentLine))
					{
						cout << CurrentLine << endl;
					}
				}
				cout << endl << "Finished reading data from " << FileName << ".";
				ReRun();
			}
			else
			{
				if(!ReadonlyFile)
				{
					cout << "File '" << FileName << "' does not exists.";
					ReRun();
				}
				else
				{
					cout << "There is a problem reading file '" << FileName << "'.";
					ReRun();
				}
			}
		}
		break;
	case 'w':
	case 'W':
		{
			cin.ignore();
			char FileName[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the name of the new file you want to create: ";
			cin.getline(FileName,FILENAME_MAX);
			fstream WriteonlyFile;
			WriteonlyFile.open(FileName,ios::out);
			if(WriteonlyFile.is_open())
			{
				cout << endl << "Enter the data you want to enter to the file. Write '[Close]' on a new line to end writing to the file: " << endl << endl;
				string NewData;
				while( (getline(cin,NewData)))
				{
					if(NewData=="[Close]")
					{
						WriteonlyFile.close();
						ReRun();
					}
					WriteonlyFile << NewData << endl;
				}
				WriteonlyFile.close();
			}
			else
			{
				cout << "Unable to create a new file '" << FileName << "'.";
				ReRun();
			}
		}
		break;
	case 'a':
	case 'A':
		{
			cin.ignore();
			char FileName[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the name of the new file you want to append contents to: ";
			cin.getline(FileName,FILENAME_MAX);
			fstream AppendToFile;
			AppendToFile.open(FileName,ios::out | ios::app);
			if(AppendToFile.is_open())
			{
				cout << endl << "Enter the data you want to append to the file. Write '[Close]' on a new line to end writing to the file: " << endl << endl;
				string NewData;
				while( (getline(cin,NewData)))
				{
					if(NewData=="[Close]")
					{
						AppendToFile.close();
						ReRun();
					}
					AppendToFile << endl << NewData;
				}
				AppendToFile.close();
			}
			else
			{
				cout << "Unable to open file '" << FileName << "' for appending.";
				ReRun();
			}
		}
		break;
	case 'c':
	case 'C':
		{
cin.ignore();
		char SourceFileName[FILENAME_MAX];
		cout << endl << "Enter the directory appended by the name of the file you want to copy: ";
		cin.getline(SourceFileName,FILENAME_MAX);
		char DestinationFileName[FILENAME_MAX];
		cout << endl << "Enter the directory appended by the name of the file you want the file to be copied: ";
		cin.getline(DestinationFileName,FILENAME_MAX);
		cout << endl << endl << "Copying " << SourceFileName << ". Please wait...";

		if(CopyF(SourceFileName,DestinationFileName))
		{
			cout << endl <<  endl << "File " << SourceFileName << " successfully copied to " << DestinationFileName << ".";
		}
		ReRun();
		}
		
		break;
	case 'm':
	case 'M':
		{
			cin.ignore();
			char SourceFileName[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the name of the file you want to move: ";
			cin.getline(SourceFileName,FILENAME_MAX);
			char DestinationFileName[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the name of the file you want the file to be moved: ";
			cin.getline(DestinationFileName,FILENAME_MAX);
			cout << endl << endl << "Moving " << SourceFileName << ". Please wait...";

			if(CopyF(SourceFileName,DestinationFileName))
			{
				remove(SourceFileName);
				cout << endl << endl <<  "File " << SourceFileName << " successfully moved to " << DestinationFileName << ".";
			}
			ReRun();
		}
		break;
	case 'd':
	case 'D':
		{
			cin.ignore();
			char FileToDelete[FILENAME_MAX];
			cout << endl << "Enter the directory appended by the name of the file you want to delete: ";
			cin.getline(FileToDelete,FILENAME_MAX);
			cout << "Deleting File: " << FileToDelete << ". Please wait...";
			if(remove(FileToDelete))
			{
				cout << endl << endl << "File " << FileToDelete << " successfully deleted.";
			}
			ReRun();
		}
		break;
	default:
		{
			cout << endl << "You have not entered a valid choice. " << endl << "Do you want to show the choices again ?";
			cout << endl << endl << "Press 'y' if you want the choices to be showed again. Press any other key and press enter to exit the program:";
			cout << endl ;
			char choice;
			cin >> choice;
			if( choice =='y' || choice == 'Y')
				main();
			else
				exit(0);
		}
	}
}
bool CopyF(char *SourceFileName,char *DestinationFileName)
{
	fstream SourceFile;
	fstream DestinationFile;
	char *Buffer;
	long SizeofFile;
	SourceFile.open(SourceFileName,ios::in | ios::binary );
	DestinationFile.open(DestinationFileName,ios::out | ios::binary );
	SourceFile.seekg(0,ios::end);
	SizeofFile = SourceFile.tellg();
	SourceFile.seekg(0);
	Buffer = new char[SizeofFile];
	SourceFile.read(Buffer,SizeofFile);
	DestinationFile.write(Buffer,SizeofFile);
	delete[] Buffer;
	DestinationFile.close();
	SourceFile.close();
	return true;
}
	void ReRun()
{
	cout << endl <<endl << "Do you wish to perform another operation ?" << endl;
	cout << "Press 'y' to perform another operation or any other key to exit the program." << endl << endl;
	cout << "Enter your choice: ";
	char choice;
	cin >> choice;
	if(choice=='y' || choice == 'Y')
		main();
	else
		exit(0);
}
My assignment. Sharing as it can be useful for others.
#15 · edited 14y ago · 14y ago
Posts 1–15 of 57 · Page 1 of 4

Post a Reply

Similar Threads

  • [Tutorial/Snippet][VB6] Reading and writing INI FilesBy That0n3Guy in Visual Basic Programming
    6Last post 16y ago
  • [Snippet] ButtonHandler - A cleaner and easier way to add button clickingBy Shakugan no Shana in Runescape Private Servers
    0Last post 14y ago
  • [Snippet]Controlable speed and gravityBy apandhi in Combat Arms Hack Coding / Programming / Source Code
    8Last post 16y ago
  • i need short icq number pls and hack to wr..By BoneXDBreaker in WarRock - International Hacks
    1Last post 20y ago
  • Lineag2 and RagnarokBy suppaman in General Gaming
    12Last post 20y ago

Tags for this Thread

#c++ gui win32