Daeto
Daeto

Reputation: 480

Passing file as an argument into my program and then into a function?

I am using CodeBlocks to create my program in C and I'm having trouble with the following issue.

I am trying to open and read from a .txt file and it works fine if I put it into the main function like this:

int main(int argc, char *argv[])
{

FILE *input;

input = fopen("file.txt", "r");

char singleLine[50];

while(!feof(input)){

fgets(singleLine, 50, input);
puts(singleLine);
}

However, if I set the name of the file "file.txt" as an argument in CodeBlock using the "Set Program's Arguments option, and then want to pass it into a function that would read from it like this:

void read(char *name){

File *input;

....
....

}

And call it like this:

int main(int argc, char *argv[])
{


read(&argv[1]);

}

It does not work and the program crashes.

Upvotes: 3

Views: 250

Answers (2)

theWalker
theWalker

Reputation: 2020

Test

read(&argv[0]);

and see what is in argv in console

printf(&argv[0]);

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

If your function prototyope is

void read(char *name)

then you need to call it like

read(argv[1]);

because , argv[1] itself gives you a char *, not &argv[1].

FWIW, always check for the validity of argv[n] before using it directly.

Upvotes: 3

Related Questions