简体   繁体   中英

How to use UNIX terminal input redirection in C?

I have this C program that gets the input from the user and sends it to a method:

#include <stdio.h>
#include <string.h>
#include "constants.h"
#include "lines.h"
#include "compare.h"

//gets arguments and sends to compare.c
int main() {
   int op = 1;
   char filename[20];

   scanf("%d ", &op);
   gets(filename);
   if ((char) op + '0' < 49 || (char) op + '0' > 57) {
       printf("Error: Invalid input");
       exit(0);
   }
   readstdin(filename, op);
   return 0;
}

but instead of executing the program and reading from stdin, I want it to read from the unix terminal so that:

./sort [field] < input_file

will read into the file. ([field] is option if no input is put in, default is 1).

For example the command to execute the C program in UNIX would look like this:

./sort 1 < test.txt

How do I go about doing this?

Any help is much appreicated Thanks!

For a start, you're getting your arguments the wrong way in your code. If what you're wanting is to run your program such as ./sort <option> <filename> , then you don't use stdin to retrieve these arguments.

The arguments in a C program are passed to main using the following function signature:

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

argc is the number of command line arguments passed to the program, and argv is the array of strings of those arguments.

With a run of ./sort 5 test.in :

  • argc will equal 3
  • argv[0] will be "./sort"
  • argv[1] will be "5"
  • argv[2] will be "test.in"

You should check that the value of argc is 3 to ensure that 2 arguments have been passed ( "5" , "test.in" ), as well as the filename ( "./sort" ) for a total of 3.


If you want to have optional fields, it would be better to have them after the compulsory ones, or better yet is to use something like getopt where you could instead have something like: ./sort --file test.in or ./sort --opt 5 --file test.in . It's probably unnecessary for this case, but it's an option.


You can parse the integer option using atoi or strtol , however you like, to convert it from a string ( char* ) to an integral type and fopen , fgets , fclose to read from the input file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM