How to parse command-line arguments from a separate function - c

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]);
}

Related

How to run a parameter while executing a C file?

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;
}

Passing argument to sub-functions in C

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;
}

put a file in argv[] of main function

hi I'm trying to write a program like this in visual C++
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main(int argc, char *argv[])
{
FILE *in;
char ch;
int openbracket=0,closebracket=0;
if(argc!=2)
{
printf("the number of arguments is incorrect");
getch();
exit(1);
}
if((in=fopen(arg[1],"r"))==NULL)
{
fputs("Error",stderr); exit(1);
}
ch=getc(in);
while(!feof(in))
{
if(ch=='{')
openbracket++;
else if(ch=='}')
closebracket++;
ch=getc(in);
}
printf("Open bracket==%d,close bracket=%d",openbracket,closebracket);
getch();
}
i am trying to open a file with argv[1] in this program in visual c++
can you please show me how i can put a file in argv[1] 0f main function?
Thank you
if((in=fopen(arg[1],"r"))==NULL);
if-statements do NOT end with a semi-colon. That makes this a "do-nothing" statement
arg is never declared anywhere (you have declared argc and argv, but not arg)

passing argument of text file from main to other function

How can I pass argument from cmd which is equal to the name of the file I want to open with other function than main?
I want to run program in cmd as "myprogram -open myfile.txt" just for example, and I want use another function to count characters or spaces or whatever in this file. How can I pass the name of file, which is in this case argv[2] to another function in which I can use fopen? thanks for your time.
int main(int argc, char **argv)
{
if((argc==3) && (strcmp("-open", argv[1]) == 0))
etc.
Simply pass in argv[2].
int main(int argc, char **argv)
{
if((argc==3) && (strcmp("-open", argv[1]) == 0))
{
FILE *fp = fopen(argv[2]);
//OR
otherFuncThatCallsFopen(argv[2]);
}
}
argv[2] is a valid char * that points to the 2nd argument.
You could write a function with signature like unsigned int count_characters(const char *file_name)
and call it with count_characters(argv[2])

Why am I segfaulting?

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.

Resources