I did this:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
HKEY CH;
if(RegCreateKey(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&CH) != 0)
{
printf("Erro - RegCreateKey\n");
system("PAUSE");
return -1;
}
if(RegOpenKey(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run",&CH) != 0) // Abre a CH "Minha CH"
{
printf("Erro - RegOpenKey\n");
system("PAUSE");
return -1;
}
if(RegSetValueEx(CH,L"PROC",0,REG_SZ,(LPBYTE) L"C:\\pasta1\\pasta2\\txt.txt",200) != 0)
printf("Erro - RegSetValue\n");
RegCloseKey(CH);
printf("\nsucesso !\n");
system("PAUSE");
return 0;
system("PAUSE");
}
Now I want do it:
if(key already exist) {
//don't make nothing
} else
Create key
...
What the function that I need to do it ? Because if not, I ever gonna create a key that already exist. And if I can avoid it would be great.
Use RegCreateKeyEx. It opens the key if it already exists, and creates it if it doesn't. lpdwDisposition parameter tells you which of these two effects actually happened. For example:
DWORD disposition = 0;
RegCreateKeyEx(..., &disposition);
if (disposition == REG_CREATED_NEW_KEY) {
/* new key was created */
} else {
/* existing key was opened */
}
Related
I am trying to create a microshell. It reads commands in, parses this and splits this, then executes. To parse, first I separate by the delimiter || to get up to two commands if there is a pipe. The split each command into an array of strings.
I thought this is how execlp works, but it only runs the command even though the C string "cmd1" does contain the arguments. Can someone please help me understand how I am passing the parameters wrong to the execlp function?
shell.h
/****************************************************************
PROGRAM: MicroShell(assignment 4)
FILE: shell.h
AUTHOR: Nick Schuck
FUNCTION: This contains the header for the shell class
****************************************************************/
#ifndef _shell_h
#define _shell_h
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
#include <pwd.h>
#include <cstring>
#include <sys/wait.h>
#include <cstdlib>
#include <vector>
class Shell
{
private:
char buffer[1024];
const char *cmd1[10];
const char *cmd2[10];
public:
Shell(); //default constructor
void askForCommand();
void readCommandLine();
void parseBuffer();
void invokeCommand();
void executeOneCommand();
void executeTwoCommands();
};
#endif
shell.cc
/***************************************************************
PROGRAM: MicroShell(assignment 4)
FILE: shell.c
AUTHOR: Nick Schuck
FUNCTION: This file contains the implementation of
class shell from file "shell.h"
****************************************************************/
#include "shell.h"
#include <iostream>
Shell::Shell()
{
/**Get current user*/
struct passwd *p = getpwuid(getuid());
if (!p) //Error handling
puts("Welcome to Nick Schuck's MicroShell, Anonymous");
/**Welcome message for my shell*/
printf("\n\nWelcome to Nick Schuck's Microshell, user %s!\n\n", p->pw_name);
}
void Shell::askForCommand()
{
/**Command Prompt*/
printf("myshell>");
}
void Shell::readCommandLine()
{
/**Read stdin into buffer array IF no*/
/**errors occur */
if (fgets(this->buffer, 1024, stdin) != NULL)
{
this->buffer[strlen(this->buffer) - 1] = 0;
}
}
void Shell::parseBuffer()
{
/**Variables*/
int i = 0, u = 0,
t = 0;
char *ptr;
char parsingBuffer[2][512];
/**Parse buffer for multiple commands*/
strcpy(parsingBuffer[0], strtok(this->buffer, "||"));
while ((ptr = strtok(NULL, "||")) != NULL)
{
i++;
strcpy(parsingBuffer[i], ptr);
}
//**Get first command*/
this->cmd1[0] = strtok(parsingBuffer[0], " ");
while ((ptr = strtok(NULL, " ")) != NULL)
{
u++;
this->cmd1[u] = ptr;
this->cmd1[u+1] = '\0';
}
//!!!TESTING TO SEE COMMAND ARE IN CMD1
int b = 0;
while(cmd1[b] != '\0')
{
std::cout << cmd1[b] << "\n";
b++;
}
/**Get second command*/
this->cmd2[0] = strtok(parsingBuffer[1], " ");
while ((ptr = strtok(NULL, " ")) != NULL)
{
t++;
this->cmd2[t] = ptr;
}
}
void Shell::invokeCommand()
{
if (this->cmd1[0] == NULL)
{
//do nothing
}
else if(this->cmd1[0] != NULL && this->cmd2[0] == NULL)
{
executeOneCommand();
}
else if(this->cmd1[0] != NULL && cmd2[0] !=NULL)
{
executeTwoCommands();
}
}
void Shell::executeOneCommand()
{
pid_t pid; //pid for fork
int status;
char args[512];
if ((pid = fork()) < 0)
{
printf("fork error\n");
exit(-1);
}
else if(pid == 0) //Child Process
{
execlp(cmd1[0], *cmd1);
}
else //Parent Process
{
if ((pid = waitpid(pid, &status, 0)) < 0)
{
printf("waitpid error in main\n");
exit(-1);
}
}
}
main.cc
#include "shell.h"
#include <iostream>
#include <vector>
int main()
{
const int BUFFER_SIZE = 1024;
const int MAX_COMMANDS_IN_BUFFER = 2;
/**Initialize a new shell object*/
Shell shell;
/**Print command prompt to screen*/
shell.askForCommand();
/**Read users command*/
shell.readCommandLine();
/**parse buffer to find individual*/
/**commands */
shell.parseBuffer();
/**Invoke command*/
shell.invokeCommand();
}
You can't use execlp() — you must use execvp().
execvp(cmd1[0], cmd1);
To use execlp(), you must know at compile time the fixed list of arguments for the command — you must be able to write:
execlp(cmd_name, arg0, arg1, …, argN, (char *)0);
Your call to execlp() is also faulty because you don't provide the (char *)0 argument to indicate the end of the argument list.
Your code also needs to handle exec*() returning, which means the command failed. Usually that means it should print an error message (that the command was not found, or permission denied, or whatever), and then exit with an appropriate non-zero error status.
So I was browsing the Internet for a project and stumbled upon this piece of code. It runs perfectly until the point you enter a website(include "www" :P) and press Enter and then boom! The program terminates, no error message, nothing.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <graphics.h>
#include <dos.h>
#include <string.h>
void initialize_graphics_mode();
int get_key();
void draw();
union REGS i, o;
main()
{
int key, i = 0, xpos, ypos, button;
char arr[200], temp[5], *ptr;
char a[] = "C:\\Progra~1\\Mozill~1\\firefox ";
strcpy(arr,a);
i = strlen(a);
initialize_graphics_mode();
draw();
while(1)
{
if(kbhit())
key = get_key();
if((key>=97&&key<=122)||(key>=65&&key<=90)||key==46||key==47||key==63)
{
arr[i] = key;
sprintf(temp,"%c",arr[i]);
outtext(temp);
if(getx()>470)
{
clearviewport();
moveto(5,2);
}
i++;
}
else if ( key == 13 )
{
arr[i] = '\0';
system(arr);
break;
}
else if ( key == 27 )
{
closegraph();
exit(EXIT_SUCCESS);
}
if(button==1&&xpos>=150&&xpos<=480&&ypos>=300&&ypos<=330)
{
system("C:\\Progra~1\\Mozill~1\\firefox programmingsimplified.com");
break;
}
key = -1;
}
closegraph();
return 0;
}
void initialize_graphics_mode()
{
int gd = DETECT, gm, errorcode;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
errorcode = graphresult();
if( errorcode != grOk )
{
printf("Graphics error : %s\n",grapherrormsg(errorcode));
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
}
int get_key()
{
i.h.ah = 0;
int86(22,&i,&o);
return( o.h.al );
}
void draw()
{
settextstyle(SANS_SERIF_FONT,HORIZ_DIR,2);
outtextxy(275,11,"Web Browser");
outtextxy(155,451,"<a> href=http://www.programmingsimplified.com"">www.programmingsimplified.com</a>");
outtextxy(5,105,"Enter URL : ");
rectangle(120,100,600,130);
setviewport(121,101,599,129,1);
moveto(5,1);
}
Could someone help me in understanding why this happens? and possibly a fix for this?
NOTE: + It is supposed to work if you have Mozilla Firefox. If you have any other browser, please edit the code accordingly.
I am running this on Turbo C++, what would I have to do in order to convert this code for Dev-C++?
Thanks in advance.
P.S: I'm new to C++ so elaborate as much as possible.
I am trying to use ncurses to get non-blocking input.
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ERR) {
printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}
However when I run this code, irrespective of what I press I always just get "here" printed.
Sample output:
Latitude-E6430:~$ ./try
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
here
dhere
ddhere
dhere
here
The d's and the spaces are not detected at all.
Can someone tell me why?
Thanks.
Finally I found the answer to the question.
I need to do initscr();
After that I am able to print out correctly (the formatting is not-as-expected though).
Correct code:
#include <iostream>
#include <ncurses.h>
int main()
{
char ch;
initscr();
nodelay(stdscr, TRUE);
while(1)
{
ch= getch();
if (ch == ' ') {
// printf("here \n");
usleep(100000);
}
else {
printf("---------------\n");
}
}
}
I am having trouble with getting input after a modifier in the text of a .txt file.
What I want to do is if the .txt file has the word "type:" then anything after that will be put into a char.
My code so far:
#include "stdafx.h"
#include <windows.h>
#include "VKH.h"
#include "Strmif.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <fstream>
void GetDocumentandRead() {
string line;
ifstream myfile (line1);
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline (myfile,line);
char aline[100];
strcpy(aline, line.c_str());
printf(aline, "\n");
if (line.compare("mouseup") == 0){
MouseUp(10);
}
if (line.compare("mousedown") == 0){
MouseDown(10);
}
if (line.compare("mouseright") == 0){
MouseRight(10);
}
if (line.compare("mouseleft") == 0){
MouseLeft(10);
}
if (line.compare("mouseclick") == 0){
MouseClick();
}
if (line.compare("enter") == 0){
Enter();
}
if (line.compare("ctrltab") == 0){
CtrlTab();
}
if (line.compare("tab") == 0){
Tab();
}
if (line.compare("altf4") == 0){
AltF4(0);
}
if (line.compare("alttab") == 0){
AltTab();
}
if (line.compare("mousecenter") == 0){
MouseCenter();
}
if (line.compare(6,5,"type:") == 0){
//Don't know what to put here...
}
}
myfile.close();
}
else printf("\nUnable to open file\n\n");
}
So after the "type:" in a text file it would type that using a function I have called TypeStr();
void TypeStr(char *lpszString)
{
char cChar;
while((cChar=*lpszString++)) // loops through chars
{
short vk=VkKeyScan(cChar); // keycode of char
if((vk>>8)&1){keybd_event(VK_LSHIFT,0,0,0);} // hold shift if necessary
keybd_event((unsigned char)vk,0,0,0); // key in
keybd_event((unsigned char)vk,0,KEYEVENTF_KEYUP,0); // key out
if((vk>>8)&1){keybd_event(VK_LSHIFT,0,KEYEVENTF_KEYUP,0);} // release shift if necessary
}
}
Any help would be appreciated. Thanks!
First you should rewrite your TypeStr function so that it takes a const char *. Like this
void TypeStr(const char *lpszString)
{
...
}
no other changes needed.
Then you should call that function from your code like this
if (line.compare(6,5,"type:") == 0){
TypeStr(line.c_str() + 11);
}
The reason that you have to change your TypeStr function to const char* (apart from it being general good style) is that the c_str() method of std::string returns a const char* not a char*.
I am building a client that:
Should be able to recieve information from both the server and the standart input
Should be able to recieve information from the server without asking, for example when another client sends a message.
To do so I tried using select to monitor both possible inputs.
What happens is that when a keyboard input is monitored I send a message to the client and I expect one back, so there's no problem. But when the server sends an unexpected message nothing happens, and I don't know why. Is using select() the proper way to do so? Is it even possible to use select() without listen()ing?
Here's my code (compileable):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <cstring>
#include <arpa/inet.h>
#include <iostream>
#include <fstream>
#define MAX_CLIENT_NAME 30
#define MAX_TWIT_SIZE 140
#define NUM_OF_ARG 4
#define ERROR -1
#define GREAT_SUCCESS 0
#define OK "OK"
#define EXIT "EXIT"
using std::string;
using std::cerr;
using std::endl;
using std::cout;
string clientName;
int srverfd, numbytes, status, maxSock ;
fd_set inputFdSet; /* Socket file descriptors we want to wake
up for, using select() */
int establishConnection(char * serverAddress,char * port){
if ((srverfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
return ERROR;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
inet_aton(serverAddress, &server.sin_addr);
server.sin_port = htons(atoi(port));
memset(&(server.sin_zero), '\0', 8);
if (connect(srverfd,(const struct sockaddr *)&server,sizeof(struct sockaddr)) == -1) {
perror("connect");
close(srverfd);
return ERROR;
}
maxSock = srverfd;
return GREAT_SUCCESS;
}
const char * getUserTweet(){
string temp;
getline(std::cin,temp);
return temp.c_str();
}
void sendMessage(string message){
if ((numbytes = send(srverfd, message.c_str(), message.length(), 0)) == -1) {
perror("sendMessage");
close(srverfd);
}
cout<<"Message sent: "<< message << endl;
return;
}
const char * getMessage(){
char buf[MAX_TWIT_SIZE];
memset(buf,'\0',MAX_TWIT_SIZE);
if ((numbytes = recv(srverfd, buf, 140, 0)) == -1) {
perror("getMessage");
close(srverfd);
}
string temp = buf;
return temp.c_str();
}
void build_select_list() {
FD_ZERO(&inputFdSet);
FD_SET(srverfd,&inputFdSet);
FD_SET(STDIN_FILENO,&inputFdSet);
if (STDIN_FILENO > maxSock)
maxSock = STDIN_FILENO;
return;
}
void readSocket(fd_set tempfd) {
const char * tweet, * inMessage;
if (FD_ISSET(srverfd,&tempfd)) {
inMessage = getMessage();
cout << inMessage << endl;
}
if (FD_ISSET(STDIN_FILENO,&tempfd)) {
tweet = getUserTweet();
sendMessage(tweet);
inMessage = getMessage();
if (strcmp(inMessage,OK) != 0) {
cout << inMessage << endl;
}
if (strcmp(inMessage,EXIT) == 0) {
return;
}
}
return;
}
int main (int argc, char *argv[] ){
int value;
bool clientON = false;
if(establishConnection(argv[2],argv[3])){
cerr << "usage: failed to make connection" << endl << "exiting..." << endl;
exit(EXIT_FAILURE);
}
cout << "Connected successfully" << endl;
sendMessage("CONNECT "+clientName); //Connect
if(strcmp(getMessage(),OK) == 0){
clientON = true;
}
while(clientON){
build_select_list();
value = select(maxSock, &inputFdSet, NULL, NULL, NULL);
if (value < 0) {
perror("select");
exit(EXIT_FAILURE);
}
if (value == 0) {
continue;
}
else {
readSocket(inputFdSet);
}
}
sendMessage("DISCONNECT");
if(strcmp(getMessage(),OK) == 0){
// do nothing
}
close(srverfd);
return 0;
}
Your select call is invalid. The first parameter must be the highest file descriptor in any of the sets, plus one.
As you have it, an event on srverfd will not "wake up" the select call (unless STDIN_FILENO was somehow less than srverfd, in which case stdin events wouldn't unlock select - but that won't happen in practice).
There are quite a few other problems with your code. (It doesn't really look like C++.)
getUserTweet is unreliable (undefined behavior - temp is destroyed as soon as the function returns, so the char* you return has disappeared by the time its caller will try to use it). Same for getMessage. To remedy that, use std::string everywhere, and only extract the char* when you call into C library functions).
readSocket needlessly copies the FD set (can be expensive).
You should really get rid of all those globals - build one or two classes to encapsulate that state and the networking functions, or something like that.