If i entered into the command line C: myprogram myfile.txt
How can I use myfile in my program. Do I have to scanf it in or is there an arbitrary way of accessing it.
My question is how can I use the myfile.txt in my program.
int
main(){
/* So in this area how do I access the myfile.txt
to then be able to read from it./*
A command line argument is simply anything we enter after the executable name, which in the above example is notepad.exe. So for example, if we launched Notepad using the command C:\Windows\System32\notepad.exe /s, then /s would be the command line argument we used.
Core Java bootcamp program with Hands on practice A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
A command-line argument is nothing but the information that we pass after typing the name of the Java program during the program execution. These arguments get stored as Strings in a String array that is passed to the main() function. We can use these command-line arguments as input in our Java program.
You can use int main(int argc, char **argv)
as your main function.
argc
- will be the count of input arguments to your program.argv
- will be a pointer to all the input arguments.
So, if you entered C:\myprogram myfile.txt
to run your program:
argc
will be 2argv[0]
will be myprogram
.argv[1]
will be myfile.txt
.More details can be found here
To read the file:FILE *f = fopen(argv[1], "r"); // "r" for read
For opening the file in other modes, read this.
Declare your main like this
int main(int argc, char* argv [])
argc specified the number of arguments (if no arguments are passed it's equal to 1 for the name of the program)
argv is a pointer to an array of strings (containing at least one member - the name of the program)
you would read the file from the command line like so: C:\my_program input_file.txt
Set up a file handle:
File* file_handle;
Open the file_handle for reading:
file_handle = fopen(argv[1], "r");
fopen returns a pointer to a file or NULL
if the file doesn't exist. argv1, contains the file you want to read as an argument
"r" means that you open the file for reading (more on the other modes here)
Read the contents using for example fgets:
fgets (buffer_to_store_data_in , 50 , file_handle);
char *
buffer to store the data in (such as an array of chars), the second argument specifies how much to read and the third is a pointer to a fileFinally close the handle
fclose(file_handle);
All done :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With