I couldn't seem to figure out how to run a cmd program in a C program.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char educode[100];
printf("Welcome To ACE-IT Edu Software!\n");
printf("\nPlease Type An Educator Code and then press enter.");
printf("\nEducator Code: ");
gets(educode);
if(educode == 5678){
system("mkdir test");
} else {
printf("\nSorry, thats not a valid Educator Code. To buy an Educator Code, go to https://www.ace-it.edu");
}
return 0;
}
Thanks to the bad if-comparison (you can't compare strings with integers) your system call is never run.
Wrong:
gets(educode);
if(educode == 5678){
Try:
gets(educode);
if(strcmp(educode, "5678") == 0 ){
Remember to add #include <string.h> to the top as well.
Also, never use gets() -- it was removed from the C standard in 2011.
Try fgets(), after reading up on how to use it.
The problem with this code is you are comparing a pointer to a string and an integer, in this line.
if (educode == 5678)
5678 is an int type, and you are determining whether or not it equals a pointer to a string of chars. C is an explicitly-typed language, so comparisons like these don't work like that. You will want to use this instead.
if (atoi(educode) == 5678)
system("mkdir test");
Use the stdlib function atoi() to convert your string to an integer value.
Side note: Using the system() function is the same way to run shell commands across all platforms (Windows, Linux, Mac). However, not all of these commands are the same. For instance, what del does in DOS-based environments, is rm in Linux/Unix. On Windows, you would use rename or move for the same action that mv does on Linux. This program is simple enough, you might just want to use a Batch file, if you're confident this code is only for Windows.
Try the solution in this link:
Calling 'ls' with execv
Make these changes:
args[0] = "/bin/mkdir"
args[1] = "new_directory"
I believe you asking for win platform
you could use the system() function available in process.h to run commands.
//Program to run dos commands through a C program.
#include <stdio.h>
#include <process.h>
int main()
{
int choice=0;
printf("\n***************************************\n");
printf("1. Open Notepad...\n");
printf("2. Get Ip Address...\n");
printf("3. Shut down the computer...\n");
printf("** Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
system("notepad");
break;
case 2:
system("ipconfig");
system("pause");
break;
case 3:
system("SHUTDOWN -S");
system("pause");
break;
default:
printf("\n Invalid choice !!!");
}
return 0;
}
Related
My program is supposed to exit when the user types in exit similar to how its done in a shell. First I checked online to see if syscall could be called in a loop, but then I noticed the indices of the characters in the array are wrong. Why are these changing; when I ran the program and typed in exit I had my program shoot out the 3rd index for testing purposes and it returned 'e'. So I thought it might've been flipped and flipped all values and my exit still did not work. Any thoughts on what the underlying issue may be?
#include <stdio.h>
//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main() { //Memory allocation
char * entry[MAX_BIN_SIZE];
while(1)
{
printf("msh>");
fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
if(entry[0]=='t' && entry[1]=='i' && entry[2]=='x' && entry[3]=='e')
{
//printf("Exiting");
exit(0); //exit(system call)
break;
printf("Inside of exit");
}
printf("msh> you typed %s %c %c %c %c",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
}
return 0;
}
I am sorry I don't have enough reputation points to add a comment, but #lundman is correct. I don't think you need to create a pointer to entry. Also, you are checking for "exit" in the reverse order. I tried and edited the code; this seems to work:
#include <stdio.h>
//Abstract: This program runs a script to emulate shell behavior
#define MAX_BIN_SIZE 100
int main()
{ //Memory allocation
char entry[MAX_BIN_SIZE];
while(1)
{
printf("msh>");
fgets(entry,MAX_BIN_SIZE,stdin); //Getting user input
if(entry[0]=='e' && entry[1]=='x' && entry[2]=='i' && entry[3]=='t')
{
printf("Inside of exit");//printf("Exiting");
exit(0); //exit(system call)
}
printf("msh> you typed %s %c %c %c %c\n",entry,entry[3],entry[2],entry[1],entry[0]); //returning user input
}
return 0;
}
What makes getch inherently unportable to be included as a standard C function?
It is so intuitive and elegant for console interfaces. Without it, asking for a single character is always misleading because users are allowed to enter more than one key.
Worse, you are often required to make sure to clear standard input after reading console input, which isn't even provided as a standard feature! I have to use my own!
A simple program which could be:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
int main(int argc, char **argv)
{
while (1) {
char yes_or_no;
printf("is this statement correct? 1 + 1 = 2(Y/N) $ ");
yes_or_no = tolower(getch());
switch (yes_or_no) {
case 'y':
puts("Right!");
goto done;
case 'n':
puts("\nhint> Please just say yes for the sake of this demo...");
break;
case 'q':
puts("\nExitting.");
goto done;
case EOF:
puts("\nEOF.");
goto done;
default:
printf("\nunknown response '%c'.\n", yes_or_no);
break;
}
}
done:
return 0;
}
becomes:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
static inline void flush_stdin()
{
char ch;
do {
ch = getchar();
} while ((ch != '\n') && (ch != EOF));
}
int main(int argc, char **argv)
{
while (1) {
char yes_or_no;
printf("is this statement correct? 1 + 1 = 2(Y/N) $ ");
yes_or_no = tolower(getchar());
switch (yes_or_no) {
case 'y':
puts("Right!");
goto done;
case 'n':
puts("hint> Please just say yes for the sake of this demo...");
break;
case EOF:
puts("EOF.");
goto done;
default:
printf("unknown response '%c'.\n", yes_or_no);
break;
}
flush_stdin(); /* remove this to see the difference */
}
done:
return 0;
}
Every time I want to make a simple portable console program, I feel forced into making a bunch of functions like that, and still end up not having all the things I want, like getch.
Sure, you could use curses, but curses takes over your whole console, and makes your program behave differently than what a regular user expects(for the program to just scroll, and still show the command you ran the program with in the console buffer).
I know "why" is a bad question(what should always be prefered), but it must be asked. Is there anything inherently unportable in getch that a desktop system can't support? If there isn't, I can just write my own and port it to all the platforms I want to support and I'm good.
If there is something getch does that can't be supported by a desktop system, what is it? So I have better reason for understanding why conio is avoided than "just use ncurses/conio is not standard".
The C standard has no notion of terminals or Windows. Anything pertaining to these things is implementation specific and cannot be part of the C programming language.
However, there are industry standards for terminal programming. One is part of POSIX (IEEE 1003.1) as the termios terminal driver interface, one is X/Open curses which specifies a library of C functions to manipulate the terminal on a higher level and the third is ISO 6429, the set of ANSI terminal escape sequences.
Incidentally, X/Open curses provides a getch() function. Microsoft Windows also supports these standards but not in a useful way.
The way you would use getch() on Windows (i.e. via conio.h) is not portable though as conio.h is a DOS specific header that cannot easily be implemented on other platforms due to the different model of how the console works in DOS vs. terminals on other platforms.
#include <stdio.h>
#include <cstdlib>
rec();
main()
{
int a, fact;
char q, n, y;
printf("\nEnter any number ");
scanf("%d", & a);
fact = rec(a);
printf("Factorial value = %d\n", fact);
printf("do you want to exit.....(y/n):");
scanf("%s" ,&q);
if (q == 'n')
{
system("cls");
main();
}
else
return 0;
}
rec(int x)
{
int f;
if (x == 1)
return 1;
else
f = x * rec(x - 1);
return f;
}
I'm using code blocks but I don't know how to clear the screen. I searched then found system("cls"); within header file #include<cstdlib>, but it shows the error cstdlib: no such file of directory. What should I do ?
Change
#include <cstdlib>
to
#include <stdlib.h>
cstdlib is a C++ header file, and thus will be unusable in C.
Clearing the screen is outside the purview of a normal C program. It depends on the operating system.
For windows, you should look into conio.
For unix, look into curses or termios.
system() always launches a sub-shell which may or may not have any effect on the environment of the parent program. You do need a system-call, but not a system() call.
I didn't always know this. I once (long ago) suggested in comp.lang.c that someone should try system("exit"); to close the window around the DOS program. But that, of course, cannot work. And I was quickly advised to test my code before posting. :)
you have lots of problems in your code....
but for the specific problem, try #include <stdlib.h>
use the #include<stdlib.h> that's where the clear screen function is defined.
To use system("cls") you need the header <iostream>. This will allow all system() types to execute. Unsure if it is a C++ header file, but it works for the compiler that I use.
Programming Language : C
I'd like to put my program in a infinite loop controlled by command line arguments..
I mean, unless I enter "quit" it should keep on executing based upon the arguments I enter to do..
Without knowing anything about your target platform, it is hard to make specific recommendations. But one way you can do it is with a "state machine." Here is a rather nice stackoverflow question that can give you some ideas. In particular look at this answer.
Try this:
#include <stdio.h>
int main(int argc,char *argv[]);
{
char cmd = '\0';
char quit = 0;
while(quit==0) {
cmd = fgetc(stdin);
switch(cmd) {
case 'q':
{
quit =1;
break;
}
// process other cases.
}
}
fprintf(stdout,"Quiting\n");
}
If I am not mistaken you can use the following function : system() in stdlib.h
where the syntax is as follows:
int system(const char *command);
here you can pass any shell command as a string argument
I have written a program in c. However once the program is finished it stops (duh). Is there a simple script that allows me to let the user start the program over again?
Why not use loop (for, while) in the main itself: ( if the program is simple!)
main()
{
while( Exit condition)
{
//logic
}
}
char cont_prog = 'n';
do {
/* main program in here */
printf("Do you want to start again? (y/n): ");
cont_prog = getchar();
} while (cont_prog == 'y' || cont_prog == 'Y');
Essentially, you want to put you main prog in a loop, asking the user if they want to continue. You have to deal with the user entering in too much data (they type, 'yes', for example) and your buffer being full next time through the loop.
If you really want to re-launch the program without exiting (though I can't see why):
Save argv (and I'll assume that argv[0] actually points to your executable, even though that is not guaranteed) if you want the same command line arguments.
Consider saving the environment, if you might change it, and also want it to be repeated.
man execv or execle. Just replace the currently running image with a new one that has the same command line
Frankly, looping would be easier, and can have the same semantics if you avoid global state, or arrange to be able to re-set it.
Sure, but how would you get the user to run that script? Wouldn't it be simpler to have the user simply re-run the program?
#include <stdlib.h>
#ifdef WIN32
#define EXECUTABLE ".exe"
#else
#define EXECUTABLE
#endif
int main(void) {
for (;;) system("executable_in_c" EXECUTABLE);
return 0;
}
Compile this program, rename your old executable to "executable_in_c[.exe]"; rename this one to the name of your old executable ... voila!