Command line arguments, reading a file
Solution 1
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 2 -
argv[0]
will bemyprogram
. -
argv[1]
will bemyfile.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.
Solution 2
-
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");
-
Read the contents using for example fgets:
fgets (buffer_to_store_data_in , 50 , file_handle);
- you need a
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 file
- you need a
-
Finally close the handle
fclose(file_handle);
All done :)
Solution 3
This is the Programming 101 way. It takes a lot for granted, and it doesn't do any error-checking at all! But it will get you started.
/* this has declarations for fopen(), printf(), etc. */
#include <stdio.h>
/* Arbitrary, just to set the size of the buffer (see below).
Can be bigger or smaller */
#define BUFSIZE 1000
int main(int argc, char *argv[])
{
/* the first command-line parameter is in argv[1]
(arg[0] is the name of the program) */
FILE *fp = fopen(argv[1], "r"); /* "r" = open for reading */
char buff[BUFSIZE]; /* a buffer to hold what you read in */
/* read in one line, up to BUFSIZE-1 in length */
while(fgets(buff, BUFSIZE - 1, fp) != NULL)
{
/* buff has one line of the file, do with it what you will... */
printf ("%s\n", buff); /* ...such as show it on the screen */
}
fclose(fp); /* close the file */
}
user2440329
Updated on March 20, 2020Comments
-
user2440329 over 4 years
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./*