So I'm trying to get the C program to read a filename from the command line in the following format: cat (filename path) | (program name)
i can get it to read the name of the input file when its entered as a command line argument, but it won't read from the concatenated argument
here's the code, right now its reading the name of the file as if written after the program name on the command line.
#include <stdio.h>
#include <string.h>
//initialize file pointer
FILE *file;
//initialize global variables
#define DEFAULT_LEN 70
//main
int main(int argv, char *argc[]){
//open File for reading
file = fopen (argc[1],"r");
//test for failure of file open, if failed, print message, quit
if(file == NULL){
printf("I'm sorry Dave, I'm araid I can't do that.\n");
printf("Open the file \"%s\" that is.\n", argc[1]);
return(0);
}
//read the first line of a file into an array
char temp[DEFAULT_LEN]; //where the read data is put
fgets(temp,DEFAULT_LEN,file); //stops at DEFAULT_LEN on \n
//print out temp
printf("%s\n", temp);
//close file, return 0 for main
fclose(file);
return(0);
}
any help would be appreciated
The reason your program can't get the file name is because you're not giving it to it.
If you run your program as:
it's given the argument
hello.txt
inargc/argv
.However, what you're doing is:
which means the shell is opening the file and feeding it into the standard input of your program. Actually, to be more accurate,
cat
is opening the file and the shell is simply connecting the standard output ofcat
to the standard input ofprog
.One way around this is to check the number of arguments (
argc
is usually the count,argv[]
the values, despite the roundabout way you have it in your code) and, if it's zero,argc == 1
, read your file from standard input.Only if an argument is given do you open that file and read it. That's the way a lot of UNIX utilities work:
Some even change their behaviour depending on how they're invoked,
wc
being one example - it shows the file name(s) if it knows them:Note that last case - because all files are being presented over the single standard input stream, there's no way to tell how many files there are.
wc
will just tally up the entire contents of that stream.Try this instead:
This allows you to use both the file and standard input method as follows:
To read from the contantenated, you need to read from STDIN
Piping content into a process does not put the values into
argv
; rather, it puts the values onto that process'sstdin
.You need to check if
argc
is greater than 1. If it is, thenargv[1]
has the filename you've been given (well, the first argument to the program, anyway). If not, you need to read fromstdin
to get the filename.