How to execute an executable with argument from within C program? - c

int s = system("./my_prog 32"); works, but how do I bring in the argument as a variable? int a = 32; int s = ("system %d", a); doesn't seem to work ("too many arguments to function 'system' ".)

The system() function in C takes a single argument of type const char *. That is why your first example works (though, your second example is malformed).
Still, what you want can be achieved using the sprintf() function in stdio.h. int a = 32; char command[80]; sprintf(command, "./my_prog %d", a); system(command);

how do I bring in the argument as a variable?
A common technique is to generate the command string dynamically, with sprintf(). For example:
char command[100];
int a = 42;
sprintf(command, "./my_prog %d", a);
int s = system(command);

Related

Newline Constants in C

My code:
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
In the above code the output:
value of area: 50
Process returned 0 (0x0) execution time : 2.909 s
Press any key to continue.
There is a new line inserted, but when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler and no newline printed out. Why???
Also, I modified my code as,
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%c", k);
return 0;
}
The output is only the area calculated and the new line but k is not printed out. I also find this very weird! Can you please give suggestions?
Please be kind enough with the suggestions and point out my mistakes because I am a beginner at C.
The problem is that you are trying to save a string as a char, so you have to change const char k = "hjk" to const char k[]="hjk" and print it using %s instead of %c.
#include<stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE ='\n';
const char k[]="hjk";
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
printf("%s", k);
return 0;
}
Some clarification: if you save a "string" without specifying that it is an array of characters char[], if you try to print it as a char %c a warning would be generater (warning: incompatible pointer to integer conversion initializing 'const char' with an expression of type 'char [4]') and if you try to print it as a array of characters %s (string) you are going to receive a segmentation fault.
when I change NEWLINE="\n" despite knowing it is a char type, there is no error prompted by the compiler
const char NEWLINE = "\n"; is invalid C. The reason why it is invalid is explained in detail here: "Pointer from integer/integer from pointer without a cast" issues
The compiler is not required to produce an "error", but it is required to produce some sort of diagnostic message. See What must a C compiler do when it finds an error?
Why your compiler decided to spew out a binary regardless of getting fed invalid C is anyone's guess. You have to ask the people who made the compiler. In case of gcc, you won't find an answer, because this is completely undocumented behavior.
And therefore, any output you get from such a "non C" program is also completely non-deterministic, unless a compiler documented the behavior among non-standard compiler extensions. gcc did not.
Similarly, const char k="hjk"; is also invalid C.
k seems an array of char.
Try to use:
const char k[] = "something";
printf("%s", k);
The statement const char k="hjk"; is not valid C code. Apparently, your compiler accepts it and assigns the memory address where the literal string "hjk" begins to k. Both a memory address and a char are implemented as integer numbers, so the memory address is interpreted as the numeric code for a character.
Because k is now, most likely, an unprintable character, printf("%c", k); will print nothing.
Exactly the same happens when you do const char NEWLINE ='\n';.

Error : format'%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat=]

I am currently trying to do my own shell, and it has to be polyglot.
So I tryed to implement a function that reads the lines in a .txt file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = *line;
i++;
}
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
}
I am on win7 but I compile with gcc on a VM.
I have a warning saying :
format'%s' expects argument of type 'char *', but argument 2 (and 3) has type 'int' [-Wformat=]
I tried to execute the prog with %d instead of %s and it prints numbers.
I don't understand what converts my aMsg into a int.
My try.txt file is just :
Hi
Quit
The contents of your text file have nothing to do with the warning, which is generated by the compiler before your program ever runs. It is complaining about this statement:
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
Global variable aMsg is an array of char, so aMsg[HI] designates a single char. In this context its value is promoted to int before being passed to printf(). The %s field descriptor expects an argument of type char *, however, and GCC is smart enough to recognize that what you are passing is incompatible.
Perhaps you had in mind
printf("%s\n%s\n", &aMsg[HI], &aMsg[QUIT]);
or the even the equivalent
printf("%s\n%s\n", aMsg + HI, aMsg + QUIT);
but though those are valid, I suspect they won't produce the result you actually want. In particular, given the input data you specified and the rest of your program, I would expect the output to be
HQ
Q
If you wanted to read in and echo back the whole contents of the input file then you need an altogether different approach to both reading in and writing out the data.
Let's take a closer look on the problematic line:
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
The string you would like to print expects 2 string parameters. You have aMsg[HI] and aMsg[QUIT]. These two are pointing to a char, so the result is one character for each. All char variables can be interpreted as a character or as a number - the character's ID number. So I assume the compiler resolves these as int types, thus providing you that error message.
As one solution you merely use %c instead of %s.
However, I suspect you want to achieve something else.
I'm completely guessing, but I think what you want is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// globals
char lang[16] = {'t','r','y'};
char *aMsg[512];
// functions
void takeFile() {
int i =0;
char namFil[32];
char lg[16];
FILE * file;
char tmp[255];
char * line = tmp;
size_t len = 0;
ssize_t read;
strcpy(namFil,"/media/sf_Projet_C/");
strcpy(lg,lang);
strcat(lg, ".txt");
strcat(namFil, lg);
file = fopen(namFil, "r");
printf("%s\n", namFil);
while((read = getline(&line,&len, file)) != -1) {
aMsg[i] = malloc(strlen(line)+1);
strcpy(aMsg[i], line);
i++;
}
fclose(file);
}
enum nMsg {HI, QUIT};
int main(void) {
takeFile();
printf("%s\n%s\n", aMsg[HI], aMsg[QUIT]);
free(aMsg[HI]);
free(aMsg[QUIT]);
return 0;
}

Printing integers passed as arguments in function in C

I am very new to C programming and having trouble compiling what should be a very simple function. The function, called printSummary, simply takes 3 integers as arguments, then prints some text along with those integers. For example, if hits=1, misses=2, and evictions=3, then printSummary(hits,misses,evictions) should print the following:
hits:1 misses:2 evictions:3
Here is the code I'm using. Thanks in advance for any advice.
#include<stdio.h>
void printSummary(int hits, int misses, int evictions)
{
printf('hits: %d\n');
printf('misses: %d\n');
printf('evictions: %d\n');
}
int main()
{
int hit_count = 1;
int miss_count = 2;
int eviction_count = 3;
printSummary(hit_count, miss_count, eviction_count);
return 0;
}
Compiling this code gives me several warnings, but no errors. When I run the code, I get a segmentation fault. Like I said, I am fairly new to C so there is most likely a simply solution that I am just missing. Thanks in advance for any advice.
Make the below changes .
printf("hits: %d\n",hits);
printf("misses: %d\n",misses);
printf("evictions: %d\n",evictions);
printf has a
int printf(const char *format, ...)
prototype. So in the first argument you can pass format specifiers and in the next provide the actual variables/values to be printed out
errors are:
void printSummary(int hits, int misses, int evictions)
{
/* Name: printf
Prototype: int printf (const char *template, ...)
Description:
The printf function prints the optional arguments under the
control of the template string template to the stream stdout.
It returns the number of characters printed,or a negative value if
there was an output error.*/
printf("hits: %d\n", hits); // don't use ' it is used only for char variable for example: char a = 'c';
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
}
Your printf function is not being called correctly. You have to include the integers needed to print:
printf("hits: %d\n", hits);
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
Read more about the printf function here.

Command line arguments in main

I've written a code that sums up integers brought in from the command line:
#include <stdio.h>
int main(int argc, int* argv[]) {
int i, s=0;
for (i=1;i<argc;i++)
s=s + *argv[i];
printf("Sum: %d\n", s);
return 0;
}
The best part is, it passes the gcc compiling process, but when I actually run it and insert the numbers, the result seems I somehow breached the range of int.
It seems that you are compiling your code in C89 mode in which s is taken as int by default by compiler. s is uninitialized therefore nothing good could be expected. If fact it will invoke undefined behavior.
Note that argv[i] is of char * type (change your main signature) and you need to convert it to int before adding it to s.
The 2nd argument of main should be either of type char** or of type char*[] and not int*[]. So, *argv[i] is of type char. Instead of getting each character, you can get each string(argv[i] which is of type char*) and then extract the number from it and assign it to a variable, say num. This can be done by using the sscanf function:
#include <stdio.h>
int main(int argc, char* argv[]) { //int changed to char here
int i, s=0,num;
for (i=1;i<argc;i++)
if(sscanf(argv[i],"%d",&num)) //if extraction was successful
s=s + num;
printf("Sum: %d\n", s);
return 0;
}
Assuming you have s initialized properly as shown below.
Along with this the prototype of your main() should be as shown below inorder to get the command line arguments.
int main(int argc, char **argv)
{
int s =0;
// Check for argc matches the required number of arguments */
for(i=1;i<argc;i++)
s=s + atoi(argv[i]); /* Use atoi() to convert your string to integer strtol() can also be used */
printf("%d\n",s);
return 0;
}
PS: Using uninitialized variables lead to undefined behvaior

C : write a function doesn't know how many parameter

When learning C I see that printf can receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, please tell me.
You need to use va_args, va_list and the like.
Have a look at this tutorial.
http://www.cprogramming.com/tutorial/c/lesson17.html
That should be helpful.
You have to use the ... notation in your function declaration as the last argument.
Please see this tutorial to learn more: http://www.cprogramming.com/tutorial/c/lesson17.html
#include <stdarg.h>
#include <stdio.h>
int add_all(int num,...)
{
va_list args;
int sum = 0;
va_start(args,num);
int x = 0;
for(x = 0; x < num;x++)
sum += va_arg(args,int);
va_end(args);
return sum;
}
int main()
{
printf("Added 2 + 5 + 3: %d\n",add_all(3,2,5,3));
}
You use C varargs to write a variadic function. You'll need to include stdargs.h, which gives you macros for iterating over an argument list of unknown size: va_start, va_arg, and va_end, using a datatype: va_list.
Here's a mostly useless function that prints out it's variable length argument list:
void printArgs(const char *arg1, ...)
{
va_list args;
char *str;
if (arg1) We
va_start(args, arg1);
printf("%s ", arg1);
while ((str = va_arg(argp, char *)) != NULL)
printf("%s ", str);
va_end(args);
}
}
...
printArgs("print", "any", "number", "of", "arguments");
Here's a more interesting example that demonstrates that you can iterate over the argument list more than once.
Note that there are type safety issues using this feature; the wiki article addresses some of this.

Resources