3

I'm struggling with accepting an argument name and passing it along to the program I have made. I made C code (copy.c) which takes in the file name and prints out in a Linux console terminal. To put it easily, it works when I do:

./copy filename.txt 

This works fine, same as what cat would produce.

However, it doesn't when I put:

./copy < filename.txt 

So I figured that "<" must be interrupting the copy to take in the next argument which is the actual file name. I was trying to get around it by first making the main to accept "< filename.txt" to the first argument as a whole and later modify it to "filename.txt"

Is there any way to get around this? If it is "123 filename.txt" this works.

Here is my copy.c:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include <string.h> #define bufferSize 200 int main(int argc, char* argv[]) { char buffer[bufferSize]; int fd; int argu_no = 1; printf("%s %s\n\n", argv[0], argv[1]); //check for the argument names return 0; } 

And when I do "./copy 123 filename.txt":

123 filename.txt 

appears.

But when I do "./copy < filename.txt"

(null) XDG_SESSION_ID=2231 

comes out. Please help me the program to accept the entire "< filename.txt" as the first argument or to get around this.

I'm using GNU library on linux for C programming.

4
  • ./copy "<" filename.txt" Commented Aug 27, 2016 at 2:38
  • I'm trying to make copy.c to take argument which doesn't start with double quotation marks like you suggested. Commented Aug 27, 2016 at 2:41
  • The quotes won't be passed in the arguments. If you want to pass the quotes explicitely you will have to escape them with a backslash. Commented Aug 27, 2016 at 2:43
  • Typo in my first comment, I meant: ./copy "<" filename.txt Commented Aug 27, 2016 at 2:44

1 Answer 1

7

The shell interprets:

./copy < filename.txt 

and treats the < and filename.txt as instructions to set standard input to the named file, and these are not passed as arguments to your program. So this invocation runs ./copy with no extra arguments (and with standard input coming from the file instead of your terminal).

If you want the < passed as an argument (and the file name too), quote it:

./copy '<' filename.txt ./copy "<" filename.txt ./copy \< filename.txt 

If there are spaces in the file name, you need to quote that, too.

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

Comments