I have a codein which i want to do the following:

main(int argc, char *argv[])
{
fp1=fopen(argv[1], "w")
function(para1, para2, ??)
}

function(para1, para2, ??)
{
fp2= fopen(argv[2], "r")
}

So eesentially i want to pass a few parameters and the pointer to the function. I dont know how to fill those ??. Should i be passing the address &argv to the function ? I tried some things but i cant figure it out.

You just pass argv[2] to the function:

void function(char* fileToOpen);
int main(int argc, char** argv) {
  FILE* fp1 = fopen(argv[1], "w");
  function(argv[2]);
}
void function(char* fileToOpen) {
  FILE* fp2 = fopen(fileToOpen, "r");
  // ...
}

when i try to compile the code i get the error:
line 12:error: conflicting types for 'function'
line 6: error: previous implicit declaration of 'function' was here

#include<stdio.h>
int main(int argc, char **argv)
{
FILE *fp1 = fopen(argv[1], "w");
fprintf(fp1, "Hello");
funct(argv[2]);
fclose(fp1);
}

void funct(char *fileToOpen)
{
FILE *fp2 = fopen(fileToOpen, "w");
fprintf(fp2, "Hello");
fclose (fp2);
}

I just get warnings rather than errors, but the problem is pretty simple. You're missing a declaration of funct. In C you need to declare (if not define) a function before calling it.

#include<stdio.h>

void funct(char*);

int main(int argc, char **argv)
{
FILE *fp1 = fopen(argv[1], "w");
fprintf(fp1, "Hello");
funct(argv[2]);
fclose(fp1);
}

void funct(char *fileToOpen)
{
FILE *fp2 = fopen(fileToOpen, "w");
fprintf(fp2, "Hello");
fclose (fp2);
}

How do we pass float/integer arguement to a C program from the commandline, if argv is a character array ??

How do we pass float/integer arguement to a C program from the commandline, if argv is a character array ??

You take that string and convert it to a particular value using some of the Standard C functions
like strtol for long integer or strtod for double, etc... and then you check that the returned result is valid and no error occurred.

This article has been dead for over six months. Start a new discussion instead.