I have a working program that computes the cube of a number in a compute_cube.c file. It compiles into compute_cube.
Now I would like to run it through the terminal like this:
./compute_cube 3
And then the terminal would show my program's result (27).
How would I go about doing this? What should I be reading up on?
Use C language's argc and argv:
int main(int argc, char **argv)
{
if (argc > 1)
printf("%s", argv[1]);
}
I know its already been answered but... argc of course = 0-based number of command line args including program name at index 0 and argv contains actual command line text.
#include <stdio.h>
int main(int argc, char **argv) {
if (argc > 1) {
int n = atoi(argv[1]);
printf ("%d^3 = %d\n", n, n*n*n);
return 0;
}
else printf("Usage: %s <num>\n", argv[0]);
return 1;
}
Related
I am attemping to parse a command-line argument from one function process_command_line which I will then use in a main function. The second command-line argument enables the name of a file input to be submitted, which will later be used to read/write files. For the time being, I will just print out the argument within the main function to ensure that it is functioning correctly. I have had no issues parsing integers using this separate function method, but cannot get a correct output when trying to parse an input file name.
EDIT: I think my issue lies in the second function where I have a line saying argv[1] = input_file;
My attempt:
#include <stdio.h>
#include <stdlib.h>
int process_command_line(int argc, char *argv[]); //declaration for command-line function
char str2[100];
int main(int argc, char *argv[]) {
printf("%s", str2);
getchar();
return 0;
}
//This function reads in the arguments
int process_command_line(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Error: Missing program arguments.\n");
exit(1);
}
//first argument is always the executable name (argv[0])
//second argument reads in the input file name
strcpy(str2, argv[1]); //I think this is where the problem lies
}
With the help of users on this question, here is my updated and functioning solution. The problem was that I wasn't calling the second function within my main function.
My solution:
#include <stdio.h>
#include <stdlib.h>
int process_command_line(int argc, char *argv[]); //declaration for command-line function
char str2[100];
int main(int argc, char *argv[]) {
process_command_line(argc, argv); //This was missing in my first attempt
printf("%s", str2);
getchar();
return 0;
}
//This function reads in the arguments
int process_command_line(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Error: Missing program arguments.\n");
exit(1);
}
//first argument is always the executable name (argv[0])
//second argument reads in the input file name
strcpy(str2, argv[1]);
}
A simple problem, but somehow I can't find the solution,
I want to pass basically, in my program one of my arguments is the desired file to send the program output to.
It's not really an issue to set it up in main() however, I'm wondering how can I process argv[] in functions that are not main.
I tried it like this:
void print_ip(struct arp* arp, char* argv[]){
char *myfile = argv[2];
if ( strlen(argv[2]) <= 0 ){
printf("ERROR: Please specify a proper interface \n");
}
else {
strcpy(myfile, argv[2]);
}
f = fopen(myfile, "w");
if (f != NULL){
printf("Found an IP address \n");
fprintf(f, "\t<ipv4>%s, %s</ipv4>", arp->ipv4_destination, arp->ipv4_source);
}
else {
printf("ERROR: Failed to open file \n");
exit(1);
}
}
This function works, only issue is when I try to launch the function from elsewhere
for example
void arp_scan(struct arp*, int bsd_socket){
... code ...
print_ip(&arp, argv);
}
i get the following error:
scanner.c: In function ‘arp_scan’: scanner.c:187:25: error: ‘argv’
undeclared (first use in this function)
print_ip(&arp, argv);
Surely there must be a way other than declaeing char *argv[] in every single function to be able to proccess it from one to another
only main can accept arguments from the command line (argv). if you want to pass these command line args to a function then you need to pass them as a paramater.
#include <stdio.h>
int passingvars(int argc, char **argv)
{
int i = 0;
while (i < argc)
{
printf(argv[i]);
i++;
}
}
int main(int argc, char *argv[])
{
passingvars(argc, argv);
return 0;
}
I am very new to C programming, and have written this C program that takes in an input N, and gives a list of all the numbers up to N that are exactly divisible by 7. The program I have written is as follows;
# include <stdio.h>
int main(){
int c,n,k;
int i=0;
int AnswerList [1000];
printf("Enter the number\n");
scanf("%d", &n);
for (c=1;c<=n;c++){
if(c%7==0){
AnswerList[i]=c;
i++;
}
}
for (k=0;k<=i;k++){
printf("%d\n", AnswerList[k]);
}
return 0;
}
I need my program to run such that if N equals 27, I should be able to type into the command line
./byseven 27
In other words, I need to write code that bypasses the printf line I think. I would appreciate any help.
Thanks a lot.
Use command-line arguments. A simple example:
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s N\n", argv[0]);
return 0;
}
int N = atoi(argv[1]); // atoi is used to convert a string to an int
// your code
}
You should use int main(int argc, char** argv) definition. Then argc will be number of your params (first param is always the name of your program), and argv is array of string which contains that params. And scanf function is not needed therefore.
gcc -o hello hello.c
It will compile and produced an exectuable file called hello. To run program type:
./hello
I'm very new to C, I am attempting to read the contents of one file character by character and output them to the stream. But even with my fopen() command commented out I receive segfault (core dumped).
I must run a command: ./a.out < testWords.in > myOut.txt to execute my file properly.
Here is what I have so far:
#include <stdio.h>
void main(char *fileName[])
{
printf("filename is %s.\n",fileName[0]);
//Get file based on a string inputed
FILE *fp=fopen(fileName[0],"r"); //Fetches our file as read only
char ch;
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
//Failed to find/open file. NULL character.
if (fp == 0) printf("Woops! Couldn't open file!\n");
//While not at end of file, grab next char.
else while( (ch=fgetc(fp)) != EOF)
{
if (ch == '\n') //on newline
{
//Prints (charCount,wordCount)\n lineCount:
printf("(%d,%d)%c%d:",charCount,wordCount,ch,lineCount);
charCount = 0;
lineCount += 1;
}
else printf("%c",ch); //mirrors char.
}
fclose(fp); //Closes file (gotta be tidy!)
}
You can't just invent a way to call main. You need to use one of the standard ways, like this:
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Missing filename\n");
return -1;
}
FILE *fp = fopen(argv[1], "r");
// ...
}
And note that argv[0] contains the program name (if available; if not it contains an empty string).
Your program segfaulted because you received the int argc argument into your char *filename[] parameter. If you ran the program with a single command line parameter, the value passed in as the first argument would have been 2, which is not a valid pointer value. The expression filename[0] dereferences that address and causes a segfault.
Any time you get a segfault in C, you should smell a bad pointer or address in an argument list. In this particular case., the signature of main is always int main(int argc, char** argv). Yours isn't.
What you want is
int main(int argc, char ** argv) {
...
FILE * fp = fopen(argv[1]); // Quiz: why argv[1]? What's argv[0]?
You're getting away with it in the compiler because, basically, luck.
I also notice in your example call, there's actually no argument in the argument list, because you're using redirection.
Use:
int main(int argc, char* argv[])
And use argv[1] as fileName.
Main function must receive always that two parameters.
I'm trying to recreate the head, and tail commands from linux for my programming class.
We just started using C so I'm new to the idea of allocating memory and pointers.
I'm wondering why this doesn't work.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv){
/* Checks if correct amount of arguements */
if(argc != 2 || argc != 4){
printf("Usage: %s head <file> \n Or: head <file> -n <number of characters>", argv[0]);
exit(-1);
}
if(strcmp(argv[1], "-n" != 0)){
char fileName[strlen(argv[1])] = argv[1];
}
}
//Compile error on char fileName[strlen(argv[1])] = argv[1];
Any additional insight would also be helpful.
I think it's better to write:
char fileName[strlen(argv[1])+1];
strcpy(fileName, argv[1]);
or (if you don't whant to make a copy of string) :
char* fileName = argv[1];
First things first, your usage doesn't match your argument checking. According to the usage, you must use one of:
head <filename>
head <filename> -n <count>
In other words, argv[1] is always the filename, argv[2] is the one that needs to be set to -n if there are more than two arguments.
Secondly, unless you want to use VLAs (variable length arrays), you should probably just set up a pointer to the filename argument with something like:
char *fileName = argv[1];
You don't need to change it at all (you'll just be passing it to fopen, presumably), so it's a waste trying to make another copy.
In addition, your if statement is wrong as an or, it should be an and. It's guaranteed that argc will either not be 2 or not be 4, since it can't be both at the same time.
I would start with something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int usage (void) {
printf ("Usage: head <file>\n");
printf (" or: head <file> -n <number of characters>\n");
return -1;
}
int main (int argc,char *argv[]) {
char *fileName;
int lineCount;
// Checks if correct arguments
if ((argc != 2) && (argc != 4)) return usage();
if ((argc == 4) && (strcmp(argv[2], "-n" != 0)) return usage();
// Get file spec and line count
fileName = argv[1];
lineCount = (argc == 2) ? 10 : atoi (argv[3]); // or strtol for purists
if (linecount < 0) lineCount = 0;
// Now go ahead and implement the logic for head.
}