Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing file contents to a c executable doesn't seem to work

I have this c executable called testFile file containing this code :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
    printf("Number of arguments : %d\n Arguments : ", argc);
    for(int i = 0; i<argc-1;i++){
        printf("%s\t", argv[i]);
    }
}

and along with it a file called test1 containing just the number 1 (echo 1 > test1)

When I call this line on the command line (zsh) :
./test < test1

the output I get is this :

Number of arguments : 1
Arguments : ./testFile

Shouldn’t this show 2 arguments ? Along with the character 1 ? I want to find a way to make this 1 appear in the arguments list, is it possible ? Or is it just the way my shell handles arguments passed like that ? (I find it weird as cat < test1 prints 1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re conflating standard input with command arguments.

main‘s argc and argv are used for passing command line arguments.

here, for example, the shell invokes echo with 1 command line argument (the 1 character), and with its standard output attached to a newly opened and truncated file test.

echo 1 > test1

here, the shell running test with 0 arguments and its standard input attached to a newly opened test1 file.

./test < test1

If you want to turn the contents of ./test1 into command line parameters for test, you can do it with xargs.

xargs test < test1

unrelated to your question:

    for(int i = 0; i<argc+1;i++){

The condition for that should be i<argc. Like all arrays in C and just about every other language, the minimum valid index of argv is 0 and the maximum valid index is argc-1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading