How to run c program and give input in same line - 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

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

You can't do that, if you use redirection (i.e. "< filename") the file is opened by the system. You could discover the name, but it's non-portable, and anyway useless since the file is already open. Just use stdin instead of fp, and you need not use fopen() (nor fclose()):
int main()
{
char buffer[1024];
// fgets() reads at most 1024 characters unless it hits a newline first
// STDIN has been already opened by the system, and assigned to data flowing
// in from our file ( < inputFile ).
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
}
A different approach is to use arguments:
int main(int argc, char **argv)
{
FILE *fp = NULL;
char buffer[1024];
if (argc != 2)
{
fprintf(stderr, "You need to specify one argument, and only one\n");
fprintf(stderr, "Example: %s filename\n", argv[0]);
// Except that argv[0], this program's name, counts.
// So 1 argument in command line means argc = 2.
return -1;
}
printf("I am %s. You wanted to open %s\n", argv[0], argv[1]);
fp = fopen(argv[1], "r");
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
fclose(fp); fp = NULL; // paranoid check
return 0;
}

You need setup your program to take a command line argument. Here's a good tutorial that solves your exact question:
http://www.cprogramming.com/tutorial/c/lesson14.html

A program's main function in C has two arguments:
int main(int nArgs, char *pszArgs[]) {}
That first argument tells the program how many parameters were passed onto the program when you ran it. Usually, this will just be 1, because it includes the program's name.
The second argument is a table of strings, which can be accessed thus (the program below prints the parameters given to it):
int main(int nArgs, char *pszArgs[])
{
int i = 0;
while (i < nArgs)
{
printf("param %d: %s\n", i, pszArgs[i]);
i++;
}
return 0;
}

Related

Read input.txt file and also output.bmp file from terminal (C-programming)

I have to do an assignment where I have to write a C-Programm, where it gets the input-file-name from the console as command line parameter.
It should move the data from the input.txt file (the input file has the information for the bmp file - color etc.) to the generated output.png file. The 20 20 parameters stand for width and height for the output.png image.
So the console-request for example (tested on Linux) will look like this:
./main input.txt output.bmp 20 20
I know that this code reads an input.txt File and puts it on the screen.
FILE *input;
int ch;
input = fopen("input.txt","r");
ch = fgetc(input);
while(!feof(input)) {
putchar(ch);
ch = fgetc(input);
}
fclose(input);
And this would (for example) write it to the output.png file.
FILE *output;
int i;
output = fopen("ass2_everyinformationin.bmp", "wb+");
for( i = 0; i < 55; i++)
{
fputc(rectangle_bmp[i], output);
}
fclose(output);
But this code works only, if I hard-code the name directly in the code, not by using a command line parameters.
I don't have any clue, how to implement that and I also didn't find any helpful information in the internet, maybe someone can help me.
Greetings
The full prototype for a standard main() is
int main(int argc, char* argv[]);
You get an int with the number of arguments, argc and
a list of "strings" (as far as they exist in C), argv.
You can for example use
#include "stdio.h"
int main(int argc, char* argv[])
{
printf("Number: %d\n", argc);
printf("0: %s\n", argv[0]);
if (1<argc)
{
printf("1: %s\n", argv[1]);
}
}
to start playing with the arguments.
Note that this is intentionally not implementing anything but a basic example of using command line parameters. This matches an accpeted StackOverflow policy of providing help with assignments, without going anywhere near solving them.

how to write a command line to a file in c

I'm having issues with writing this command line to a file and it's suppose to output to the screen. To me, my code looks like it should work but I'm at a complete loss (this is my first time programming in C)
Print one line describing your program
Open the first parameter as a file for writing. If no parameter is provided, write to the stdout handle
Using a loop, save the contents of the array of string pointers passed as a parameter to the main function into the file open for writing. This is usually the variable named argv.
int main(int argc, char *argv[])
{
FILE *fp;
int i;
printf("Output supplying 'multiple arguments' to this program");
fp = fopen(argv[1], "w"); //Write to file
if(fp==NULL)
{
fp = stdout;
}
for(i=0;i<argc;i++)
{
fprintf(fp, argv[i]);
}
printf("The number of arguments printed %d", argc);
return 0;
Any help provided would be greatly appreciated!
Don't ever use dynamic format strings in C. This opens you up to an extensive set of bugs, several of them security-sensitive. Instead, pass a format string that indicates your intent, like so:
for(i=0;i<argc;i++)
{
fprintf(fp, "%s\n", argv[i]);
}

reading data from a file into an array error in C

I am trying to read from a file specified in a command prompt through terminal using the line program < file.txt and then print it again to check it works. I get the error Segmentation fault: 11, I'm not sure if my file is opening correctly in my program.
This is the code so far:
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
Any help or feedback would be greatly appreciated.
You should execute your program like
./program file.txt
I'm not sure if my file is opening correctly in my program
Then you should really test for it, you are getting a segfault because fopen is returning NULL.
#include <stdio.h>
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
if (!fp) {
printf("Invalid file name \n");
return -1;
}
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
fopen is NULL because you are invoking the program in the wrong manner, < and > are a re-directions which can be useful but is not what you are trying to do in this case, correct way to invoke it is to simply pass it the arguments directly.
./program input.file
Yeah, either:
1) check the way you're invoking it, i.e,
check if the 'program' is an executable file, you can make it executable using chmod command in linux
check if the path to 'program' or 'file.txt' is correct
2) (I'm not sure of this): check if the content of 'file.txt' is of the right content. (I don't think it should affect to the extent that it causes a segmentation fault, but still, check it.)

C - main() command line parameters

This is a really basic question but I can't find a definitive answer anywhere.
I understand the parameters of main, as far as what they refer to:
int main(int argc, char *argv[])
where argc refers to the number of command line arguments and argv refers to the array that holds each of the strings. I created an exe file of the source code from the .c file, but have no experience with command prompts and don't understand the syntax of the command line arguments.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *infile, *outfile;
int iochar;
if(argc != 3){
printf("Usage: filename infile outfile\n");
exit(1);
}
if((infile = fopen(argv[1], "r")) == NULL){
printf("Can't open input file.\n");
exit(1);
}
if((outfile = fopen(argv[2], "w")) == NULL){
printf("Can't open output file.\n");
exit(1);
}
while((iochar = getc(infile))!=EOF){
putc(iochar, outfile);
}
fclose(infile);
fclose(outfile);
printf("You've reached the end of the program.\n");
return;
}
The preceding code should take 3 arguments and copy the 2nd argument's contents into the 3rd argument's location. What do I have to do for this to happen?
You can set the command line arguments in the Debug properties of your VS project.
don't understand the syntax of the command line arguments.
The details of the syntax of the command line arguments depends on what program is interpreting them ... VS, a Windows shortcut, Windows cmd, bash, etc. ... but generally it's just a list of items separated by spaces. If the items themselves contain spaces, quotes, or other special characters, then you need to pay attention to the rules of the interpreter you're using.
The semantics of the command line arguments is defined by your program ... in this case, the first argument is the name of the input file and the second argument is the name of the output file.
printf("Usage: filename infile outfile\n");
This is not a good usage message ... the "filename" should be the name of your program, which is generally the value of argv[0]. Thus:
printf("Usage: %s infile outfile\n", argv[0]);

C How to take multiple files for arguments?

How would you ask for the user to input files as arguments to be used (as many as they would like)? Also How would you print to a file?
scanf("%s", user_filename);
FILE *fp;
fp = fopen (user_filename, "r");
I have tried doing various things to it but I can only get it to take one file.
The easiest way to pass some file names to your C program is to pass them as arguments to your C program.
Arguments are passed to a C program using the parameters to main:
int main( int argc, char *argv[] )
{
...
}
The value argc indicates how many parameters there are, and argv[] is an array of string pointers containing the arguments. Note that the first argument at index 0 (the string pointed to by argv[0]) is the command name itself. The rest of the arguments passed to the command are in argv[1], argv[2], and so on.
If you compile your program and call it like this:
my_prog foo.txt bar.txt bah.txt
Then the value of argc will be 4 (remember it includes the command) and the argv values will be:
argv[0] points to "my_prog"
argv[1] points to "foo.txt"
argv[2] points to "bar.txt"
argv[3] points to "bah.txt"
In your program then, you only need to check argc for how many parameters there are. If argc > 1, then you have at least one parameter starting at argv[1]:
int main( int argc, char *argv[] )
{
int i;
FILE *fp;
// If there are no command line parameters, complain and exit
//
if ( argc < 2 )
{
fprintf( stderr, "Usage: %s some_file_names\n", argv[0] );
return 1; // This exits the program, but you might choose to continue processing
// the other files.
}
for ( i = 1; i < argc; i++ )
{
if ( (fp = fopen(argv[i], "r")) == NULL )
{
fprintf( stderr, "%s: Gah! I could not open file named %s!\n", argv[0], argv[i] );
return 2;
}
// Do some stuff with file named argv[i], file pointer fp
...
fclose( fp );
}
return 0;
}
This is just one of several different ways to do it (functionally and stylistically), depending upon how you need to process the files.

Resources