Reputation: 13
I have the following simple program. And I am running "program file.txt" from the command line and getting "Bus error" with no output. I don't know what I'm doing wrong here.
#include<stdio.h>
int main(char *arg[])
{
FILE *file = fopen(arg[0], "r");
if (file == NULL) {
printf("Cannot open file.\n");
exit(1);
}
return 1;
}
Upvotes: 1
Views: 1343
Reputation: 97707
The prototype for the c entry function is
int main(int argc, char *arg[]);
So with your prototype you are actually trying to dereference an int to passing to fopen
Try this instead
#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *file = fopen(argv[1], "r");
if (file == NULL) {
printf("Cannot open file.\n");
exit(1);
}
return 1;
}
Upvotes: 3
Reputation: 76725
The standard prototype for main()
should look like this:
int main(int argc, char * argv[]);
You declared your main()
with just one argument, argv
. But the system is passing a count of arguments as the first argument.
When you specify a single argument (the file file.txt
), argc
is set to 1. But your program is trying to use the integer 1 as a char **
. That gives the bus error.
Here is an edited version of your program that works:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *file;
if (argc != 2)
{
fprintf(stderr, "Usage: myprogram <filename>\n");
exit(1);
}
file = fopen(argv[1], "r");
if (file == NULL) {
fprintf(stderr, "Cannot open file.\n");
exit(2);
}
exit(0); // status 0 to signal no error
}
Changes:
I added #include <stdlib.h>
to get a declaration of exit()
.
I check the number of arguments and print a Usage: string if it's not right.
I made the error messages print to stderr
instead of standard output.
I changed return 1
to exit(0)
to make it clear that the program is exiting successfully.
Upvotes: 1
Reputation: 3678
could you print out the value of arg[0], suppose the type of main is
int main(int argc, char* argv[])
and the argv[0] is the name of process, the argv[1] is first argument.
Upvotes: 2