Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run c program and give input in same line

Tags:

c

I'm new to C and I'd like to ask about running a C program and supplying input at the same time.

What I would like to do is run a program (ex. fileOpener) and also state which file to open

./fileOpener < filename1

I've tried it already and it works fine, but what do I use to know what filename1 is? That way I can open the file with

fp = fopen(filename1, "r")

Thanks.

Edit: OK, I'll try to explain a bit more. If there wasn't a "<" then I could just use command line arguments as I have done before, but when I tried it with the <, it didn't work

Specifically: fileOpener code:

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

int main(int argc, char *argv[]){
printf("%s", argv[1]);
}

when I use ./fileOpener < filename1 the output is ./fileOpener

I used gcc -o fileOpener fileOpener.c as the compiler

like image 207
emanyalpsid Avatar asked Dec 06 '25 19:12

emanyalpsid


1 Answers

int main(int argc, char *argv[])

You can name them whatever you want, but these are the normal names.

argc is non-negative. It gives the number of useful elements in argv.

If argc is positive, argv[0] contains the program name. Then argv[1] through argv[argc - 1] point to character arrays that contain the program's command line arguments.

For example, if I run a program at the command line, such as

unzip filename.zip

argc will equal 2; and argv[0] will compare equal to "unzip"; and argv[1] will compare equal to "filename.zip".

Source

like image 68
MyBoon Avatar answered Dec 08 '25 12:12

MyBoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!