Command line execution of C program - c

I have a written a C program using Visual Studio 2008. The program compares to files in binary mode and tells us if the files are same or different.
I need to execute this program on command line and need to pass 2 arguments along with it.
the first argument is for the file to be compared and 2nd is the file to which it will be compared.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int result_code;
char command_line[256];
sprintf(command_line, "FC /B %s %s > NUL:", argv[1], argv[2]);
result_code=system(command_line);
printf("%s file.\n", result_code ? "different" : "same");
return 0;
}

See this.
http://www.cprogramming.com/tutorial/print/lesson14.html
you can get plenty more from google.

Related

Pass the arguments received in C down to bash script

I have the following piece of C code that is being called with arguments:
int main(int argc, char *argv[])
{
system( "/home/user/script.sh" );
return 0;
}
how do i pass all arguments received down to script.sh?
You could synthesize some string (escaping naughty characters like quote or space when needed, like Shell related utility functions of Glib do) for system(3).
But (on Linux and Posix) you really want to call execv(3) without using system(3)
You may want to read (in addition of the man page I linked above) : Advanced Linux Programming
I think that you are looking for the execv function. It will grant to you to execute a specific file passing to it some optional arguments.
Try something next:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
system("cat /etc/passwd");
extern char * const environ[];
char * const command[] = {"mylsname", "-lR", "/", NULL};
execve("/bin/ls", command, environ);
perror("execve");
exit(EXIT_FAILURE);
}
You can use snprintf() function to frame a string. For example, snprintf(filename, sizeof(char) * 64, "/home/user/script.sh %s", argv[1]); and use system(filename);

MSVS command line arguments

#include "hmap.h"
int main(char* argv[], int argc)
{
printf("%s", argv[0]); <---- fails here
system("pause");
fileOpen(argv[1]);
return 0;
}
I am using MSVS 2012. I'm wondering if I'm using the command line arguments wrong. The text file is in the same folder. All my header file has is the #include libraries I will using, some #define's I'll be using, and extern function prototypes.
When I run the program it says "expand.exe has stopped working...."
I usually program in a Linux environment using GCC but I'm trying to learn MSVS environment. Getting a little frustrated on how much of a hassle to input command line arguments :.
I think the arguments for main() are around the wrong way.
That is, the first argument should be the argument count (argv), and the second one the argument vector (argv).
int main(int argc, char* argv[]) {}
It fails because a subscript should be used only with an array or pointer.

fopen() and command line arguments

I'm trying to write a program that will read the first character in a text file. If I use ./a.out myfile.txt it works as intended but if I use ./a.out <myfile.txt I get Segmentation fault: 11. The reason why I'm trying to include the <is because this what is in the spec of the assignment. The below code is just a simplified example that i've made that has the same issue:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int func(int argc, char **argv){
FILE *fp;
int test = 0;
fp = fopen(argv[1], "r");
fscanf(fp, "%i", &test);
printf( "current file: %s \n", argv[1]);
}
int main(int argc, char **argv){
func(argc, argv);
}
Is there any way I can get it to accept the argument as <myfile.txt?
No, nor should you try. Files redirected this way will appear at stdin and you should use that instead (hint: check argc).
If you want to use a file if specified, but otherwise stdin, use something like:
if (argc > 1)
fp = fopen(argv[1], "r");
else
fp = stdin;
In your command ./a.out <myfile you redirect stdin to myfile. This means reading from stdin is actually reading from myfile. So, in this case your argc == 1, so argv[1] you use to open is NULL (see main spec on its arguments). fopen crashes when uses NULL name.
You may do your utility in another way: always read stdin. When you need file to input do like this: cat myfile | ./a.out. This is very nice approach and worth considering.

command line arguments not working on visual c++ express 2010

I am having an issue passing command line arguments to my program using Visual C++ Express 2010. I found the command arguments under debugging and using the following input, just the terms with white space between them. The file is in my project folder with the .c source code.
TestFile1.txt 2
The program works fine when I just statically define the char pointer under main. So at this point I'm not sure if the issue is with 2010 or the code. I haven't figured out a way to compile and execute in some other way to test command line args. It would be great if someone could compile this an see if it works on their system.
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 256
int main(char *argv[])
{
//char *argv[] = { "program", "TestFile1.txt", "2" };
char buf[BUFFER_SIZE];
FILE *inFp;
printf("%s",argv[1]);
if ((inFp = fopen (argv[1], "r")) == NULL)
{
fprintf(stderr, "Can't open file\n");
exit(EXIT_FAILURE);
}
fclose(inFp);
return 0;
}
it should be int main(int argc, char *argv[]) Other than that, I have not seen any other problem with your program.

Reading command line parameters

I have made little program for computing pi (π) as an integral. Now I am facing a question how to extend it to compute an integral, which will be given as an extra parameter when starting an application. How do I deal with such a parameter in a program?
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main are:
int argc - the number of arguments passed into your program when it was run. It is at least 1.
char **argv - this is a pointer-to-char *. It can alternatively be this: char *argv[], which means 'array of char *'. This is an array of C-style-string pointers.
Basic Example
For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c. It'll compile and build a default a.out executable.
[birryree#lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree#lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv, argv[0] is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1] and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
A Simple Case for You
And you could check if argv[1] was integral, maybe like strcmp("integral", argv[1]) == 0.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Better command line parsing
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project.
http://tclap.sourceforge.net/
A similar library is available for C as well.
http://argtable.sourceforge.net/
There's also a C standard built-in library to get command line arguments: getopt
You can check it on Wikipedia or in Argument-parsing helpers for C/Unix.

Resources