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.

Recommended Answers

All 8 Replies

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

could you post the code please? And be sure to use [code] and [/code] tags :)

#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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.