How to close windows using c program where user enters time

I have been studying c and I want to create a c program, all it has to do is shutdown the computer after a certain time of user input.

I know how to do an immediate close using this code:

#include<stdlib.h>
int main()
{
 system("C:\\WINDOWS\\System32\\shutdown /s /t 00");
 return 0;
}

      

I create an .exe file and execute it, it works fine. but I don't know how to shutdown after a while when the user logs in. I tried the # operator like:

#include<stdio.h>
#include<stdlib.h>
#define shutown(x) system("C:\\WINDOWS\\System32\\shutdown /s /t" #x);

int main()
{
  int t;
  printf("\n enter secs :");
  scanf("%d",t);
  shutdown(t);
}

      

but the program didn't work. I never used # operator, but did a search on it:

https://msdn.microsoft.com/en-us/library/7e3a913x.aspx

http://www.complete-concrete-concise.com/programming/c/preprocessor-%E2%80%93-understanding-the-stringizing-operator

but I'm still not sure if I'm using the operator correctly.

I would also like to create a program that would create a folder in windows with a username, but I was planning on using the # operator and I think I am doing something wrong.

please tell me where i am going and any other logic to accomplish the same tasks.

Many thanks!

+3


source to share


2 answers


An operator #

is a preprocessor operator, that is, everything is done at compile time. You cannot use values ​​from the user there. What you actually get is:

system("C:\\WINDOWS\\System32\\shutdown /s /t" "t");

      

This is definitely not what you want.

You really want to have a local string buffer that you will print the value to using something like sprintf

and then callingsystem(buffer);




This will do what you want:

int main()
{
  int t;
  char buffer[100];
  printf("\n enter secs :");
  scanf("%d",&t); // Note that you need &t here
  sprintf(buffer, "C:\\WINDOWS\\System32\\shutdown /s /t %d", t); 
  system(buffer);
}

      

+4


source


Your expression #define

shutdown

says shutown

(copy + paste error?).

To use a variable in a macro #define

, just enter the variable name. Example:

#define shutdown(x) system("C:\\WINDOWS\\System32\\shutdown /s /t" x);

      

but call any functions in the macro as if you were calling them elsewhere. It does not replace x

with a value t

, it replaces it with a literal t

. Hence,

system("C:\\WINDOWS\\System32\\shutdown /s /t" t);

      



will not work. You will need to concatenate the two lines with something like strcat

.

You will need #include <string.h>

to use strcat

, but after you did that changed shutdown

:

#define shutdown(x) system(strcat("C:\\WINDOWS\\System32\\shutdown /s /t ", x));

      

DISCLAIMER: I have not tested any of these codes, this is just a general guide. There might be problems, but that's the gist of what will work. Think of this as psuedocode.

0


source







All Articles