Question
How can I read from argv[0]
? I'm using NetBeans. Everytime, I have to type in stdin. When I use argv
, then the program executes without my input.
Here's my code:
int main(int argc,char *argv[])
{
char *text;
int textLen,repNum;
text = stream2string(stdin,&textLen);
//....text = argv[0] doesnt work :(
UPDATE:
When I compile and run, I have to Type an Example String! The string is always the same: ABAABAABBBA
. So I will take the first argument instead of stdin. But argv[1]
doesn't work either.
Here's stream2string()
:
char *stream2string (FILE *fptr, int *n)
{
static char *s;
*n = 0;
ALLOC(s,char,2);
s[*n] = getc(fptr);
while(s[*n]!=EOF && s[*n]!='\0' && s[*n]!='\n') {
REALLOC(s,char,++*n+2);
s[*n] = getc(fptr);
}
s[*n] = '\0';
return(s);
} /* stream2string() */
I think setting textLen
is also important.
Solution
argv[0] is the name of your executable; I don't think you want to read from that! Rather, I think you want to open argv[1] (the filename given as the first argument to your program on the commandline) and read that:
int main(int argc,char *argv[])
{
char *text;
int textLen,repNum;
FILE *theinput;
if (argc < 2) {
/* no argument */
/* give error message and exit */
fprintf(stderr, "Must pass an argument!\n");
exit(1);
}
theinput = fopen(argv[1], "r");
if (!theinput) {
/* Argument is non-existing file */
/* give error message and exit */
fprintf(stderr, "Can't read %s\n", argv[1]);
exit(1);
}
text = stream2string(theinput, &textLen);
fclose(theinput);
etc. (Of course you can and should provide more detailed and helpful error messages, etc, etc, but I'm trying to focus on the key points that you appeared to be missing).
Edit: ah well, focus seems out of fashion, judging from the comments, so I just edited to provide minimally acceptable error messages.
OTHER TIPS
Try to use argv[1] instead to read the first argument. argv[0] returns the name of the executable that was called (or the name of the link to the executable on Unix/Linux systems).
This sounds like you haven't set the program arguments for when it is run in the IDE. This is a NetBeans issue - nothing to do with C.