How to use arguments with fopen? - c

I have to write a C program that uses arguments like this :
App.exe -in file.txt
I know something about argv and char *argc but..how do I use the argument with fopen?That i don't know!

[Note that this doesn't answer the question, but it do show how to use arguments]
Learn about the arguments first, and how they are handled. Then you know how to use the arguments and pass a filename on to the fopen (or any other) function.
Try this little program first:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
for (size_t a = 0; i < argc; ++a)
{
printf("argv[%zu] = \"%s\"\n", a, argc[a]);
}
}
If you execute this program like
args.exe -in file.txt
the output should be
argc = 3
argv[0] = "args.exe"
argv[1] = "-in"
argv[2] = "file.txt"

You need to parse argv to check if it's contains what you want.
int main(int argc, char** argv)
{
if (argc < 3)
{
printf("bad usage");
}
if (strcmp(argv[1], "-in") == 0)
{
char* filename = argv[2];
FILE* f = fopen(filename);
}
}

Related

Cannot read Command Line Arguments into integer Array C

I'm trying to use command line arguments and have it read into an array however the complier is giving me this error:
error: invalid initializer
I know I need to use int main(int argc, char *argv[]) to use command line arguments and then I have it set like this to read into the array:
int arr[] = atoi(argv[1]);
Not sure what I am missing as this always worked for me in the past. Any ideas?
If what you are passing through the command line a series of number and you want
to have them in an array, then you can do this:
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stderr, "not enough arguments\n");
return 1;
}
int arr[argc-1];
for(size_t i = 0; i < argc - 1; ++i)
arr[i] = atoi(argv[i+1]);
...
return;
}
The reason why the conversion starts at argv[i+1] and not argv[0] is because
argv[0] has always the string that contains the file name of the executed
binary (more precisely the was you've passed the command in the shell), so
argc is always at least 1. That's why the dimension of arr is argc-1,
because for n arguments, argc will be n+1.
Also be aware that atoi does a poor job when it encounters an error, if the
string is not an integer, then atoi will return 0 and you have no idea whether
this is a legit number of an error in the conversion. Using strtol is a
far better alternative:
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stderr, "not enough arguments\n");
return 1;
}
int arr[argc-1];
char *endptr;
for(size_t i = 0; i < argc - 1; ++i)
{
arr[i] = strtol(argv[i+1], &endptr, 0);
if(*endptr != 0)
{
fprintf(stderr, "The argument #%d is not a number\n", i+1);
return 1; // error
}
}
...
return;
}
This would give you a far better result, because it reacts to error from the
user.

Integer and a filename as two command-line arguments in C

I want to send the size of an 2D array and filename as command line arguments in C.
int main(int argc,char *argv[])
I know this works for single arguments, but how do I take two arguments?
argc tells you the number of arguments.
argv is an array of char pointers to c-style strings.
So you can simply print all arguments by:
int main(int argc, char *argv[])
{
int i;
for (i=0; i<argc; ++i)
{
printf("%s\n", argv[i]);
}
}
You can use atoi to convert (the initial portion of) a string to an integer.
So you can do something like:
int main(int argc,char *argv[])
{
char filename[100];
int size = 0;
int i;
if (argc < 3)
{
printf("Too few arguments\n");
return 0;
}
if (strlen(argv[1]) >= 100)
{
printf("File name too long\n");
return 0;
}
strcpy(filename, argv[1]);
size = atoi(argv[2]);
if (size <= 0)
{
printf("Invalid size\n");
return 0;
}
....
....
return 0;
}
Note that it is usually not necessary to copy file name arguments to another variable unless you are going to modify the value in some way.

bash + c pipe parameter

How can I access piped parameter in c code?
test.c
int main( int argc, char *argv[] ) {
int i = 0;
for (i = 0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
}
Bash:
cat file.txt | ./test
It prints just first argument argv[0] = ./test. How can I access content of file.txt inside c code (as parameter)?
With the pipe, your program gets the content of file.txt in its stdin. So, read from stdin. For example you can use fgets() to read line by line:
#include <stdio.h>
int main(int argc, char *argv[]) {
int i = 0;
char line[1024];
while(fgets(line, sizeof line, stdin)) {
printf("%s", line);
}
}

concatenate each value of argv with a string

I'm working on a C program that get the command line arguments and append to them a file extension.
The execution will be something like this:
>myprogram file1 file2
and will execute another program that will use as argument file1.txt and file2.txt.
I tried doing that would add the extension and run one command (s1 is the path and s2 is argv[i] on a loop:
int getfile(char *s1, char *s2){
char *str2 = malloc(sizeof(s2)+3);
strcpy(str2,s2);
strcat(str2,".txt");
execl(s1,"program",str2,NULL);
exit(0);
}
The function will run the program for one file (>program file1.txt and >program file2.txt), but I will need to find a way to run it this way (>program file1.txt file2.txt).
I tried to modify argv directly, but I was unsuccessful.
Any advise?
Try this code:
int main(int argc, char *argv[])
{
char *buffer;
char command[512];
int i = 1;
for(i = 1; i < argc; i++){
buffer = malloc(strlen(argv[i]) + 5);
strcpy(buffer,argv[i]);
strcat(buffer,".txt");
sprintf(command,"touch %s\0",buffer);
system(command);
free(buffer);
}
return 0;
}
A simple program that has no error checking, and I like to explicitly add the string terminator.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, int *argv[]){
if(argc==1){
printf("You have not entered anything!\n");
return 0;
}
char *arr=malloc(1000*sizeof(char));
int i;
strcat(arr, argv[0]);
strcat(arr, " ");
for(i=0;i<argc-1;i++){
strcat(arr,argv[i+1]);
strcat(arr,".txt");
strcat(arr," ");
strcat(arr,"\0");
}
printf("%s\n",arr);
free(arr);
return 0;
}

Sending a FILE pointer to a function for reading

I've been working on this thing for hours on end and I have searched and searched and my code still does not work right.
How do I read my FILE from a function within main using argv[] as the file that I want read?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
FILE words(FILE *filesToRead)
{
const char *Open;
Open = (char *)filesToRead;
filesToRead = fopen(Open, "rt");
int line;
while ((line = fgetc(filesToRead)) != EOF)
{
printf("%c", line);
}
fclose(filesToRead);
}
int main(int argc, char *argv[])
{
char *ah = argv[];
words(ah);
return 0;
}
Try this:
void words(char *filename)
{
FILE *filesToRead = fopen(filename, "rt");
/* ... */
}
int main(int argc, char *argv[])
{
if (argc > 1)
words(argv[1]);
return 0;
}
To be honest (and please don't be offended) the way your code looks it seems you have skipped a few chapters in the C book you are using.
argv[] is an array of char *s. For example, if you call your program from the command line as:
my_prog.exe foo bar
Then:
argc will be 3;
argv[0] will point to "my_prog.exe"
argv[1] will point to "foo"
argv[2] will point to "bar"
So inside your main() function, if you are expecting one argument you will need to check the value of argc is 2 and then read your argument out of argv[1].

Resources