3

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.

1

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Hey there and thanks for your reply!I definitely made a mistake there but it still does not work. Maybe something to do with the location of the file?
@Daeto after checking argc > 1 try printing the file name in main() and again in read(). You must also test input == NULL after attempting to open the file. Finally please don't use read() as a function name - it's already used for a library function.
The printf function prints the name of the file both in main and in the read function so I guess passing the name of the file as an argument is not being an issue here. However, I added the condition to check whether opening the file was successful, it it turns out that it was not. Any idea why? The commands in the function look just like I described them above in main.
@Daeto you are opening the file for reading, so it must it already exist, on a path that the program will look in.
@Daeto you have shown code for what worked, but you didn't show the code for what did not work.
|
0

Test

read(&argv[0]);

and see what is in argv in console

printf(&argv[0]);

2 Comments

I'm confused. Sourav said I should not be passing arguments into the read function like this. Also, argv[0] is the location of my program isn' t it? Why would I need that? If I print argv[1], it prints file.txt which is the name of the file located in the same directory as my program. So I guess it is really there.
printf(&argv[0]); is really a bad example, even ignoring the logic, whatsoever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.