Reputation: 35
i've been learning c , and i want to create a c program , all it should do is to shutdown the computer after a certain user entered time.
i know how to perform an immediate shut down , using this code :
#include<stdlib.h>
int main()
{
system("C:\\WINDOWS\\System32\\shutdown /s /t 00");
return 0;
}
i create the .exe file , and execute , it runs fine. but i don't know how to shutdown after some time that the user enters. i tried the # operator as :
#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 did not work. i've never actually used # operator , but did search on it , here :
https://msdn.microsoft.com/en-us/library/7e3a913x.aspx
but , i'm still not sure if i'm using the operator correctly.
i'd also like to create a program , which would create a folder in windows with user entered name , but i was planning to use # operator , and i guess i'm doing something wrong.
please tell me where am i going wrong , and any other logic to perform the same tasks.
thanks a lot !
Upvotes: 3
Views: 179
Reputation: 1084
In your #define
statement, shutdown
is spelled shutown
(copy+paste error?).
To use a variable in a #define
macro, just put the name of the variable. 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 substitute x
for the value of t
, it substitutes it for the literal t
. Therefore,
system("C:\\WINDOWS\\System32\\shutdown /s /t" t);
will not work. You will need to concatenate the two strings with something like strcat
.
You will need to #include <string.h>
to use strcat
, but after you've done that here's a modified shutdown
:
#define shutdown(x) system(strcat("C:\\WINDOWS\\System32\\shutdown /s /t ", x));
DISCLAIMER: I have not tested any of this code, it's just a general guide. There may be problems, but this is the gist of what will work. Treat it as psuedocode.
Upvotes: 0
Reputation: 2902
The #
operator is a preprocessor operator, meaning it is all done at compile time. You cannot use the values from the user there. You actually end up with:
system("C:\\WINDOWS\\System32\\shutdown /s /t" "t");
Which is definitely not what you want.
You actually want to have a local string buffer to which you will print the value, using something like sprintf
and then calling system(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);
}
Upvotes: 4