Home > database >  Use a txt file to send input to my C program
Use a txt file to send input to my C program

Time:03-30

#include<stdio.h>  

int main()   
{   
  int n, count = 1;   
  float x, average, sum = 0;   
  printf("How many numbers do you wish to test: ");  
  scanf ("%d",&n);   
  while (count <= n)   
     {   
      printf ("Enter number #%d: ",count);   
      scanf("%f", &x);   
      sum  = x;   
        count;   
     }   
    average = sum/n;   
    printf("\nThe Average is: %.2f\n", average);   
}  

This program asks the user for a certain amount of numbers to be entered and then calculates the average of those numbers. My question is, if I want to use a file called inputfile.txt to input the data, how would I use redirection without typing in the data from STDIN? So instead the data comes from the inputfile.txt. Also how would I set up the inputfile.txt?

CodePudding user response:

You'd put your numbers in a text file, one per line.

Then, because you need to enter the count first, use the wc command

$ gcc your_code.c

$ cat numbers
10
20
40

$ { wc -l < numbers; cat numbers; } | ./a.out
How many numbers do you wish to test: Enter number #1: Enter number #2: Enter number #3:
The Average is: 23.33

I use the braces to group the output of both wc and cat into a single input stream for your program.


A bash-specific technique: read the numbers from the file into a shell array, and then use printf to output the length of the array and the array elements.

$ readarray -t nums < numbers

$ printf '%d\n' "${#nums[@]}" "${nums[@]}" | ./a.out
How many numbers do you wish to test: Enter number #1: Enter number #2: Enter number #3:
The Average is: 23.33

CodePudding user response:

Simply create a file with compatible content. And then redirect using <. For example, file content is:

5
1
2
3
4
5

The first number is number of numbers. Others are numbers you want to calculate average. Save this file as any name like file.txt and then call your program like this: ./a.out < file.txt.

You should think about < is only redirects file content to stdin. So file content should same with writing answers from stdin interactively. If you set first number to 5 in file and then set 4 different number, your program will ask for 5th number(sorry). Your program won't ask for 5th number. See comments.

  • Related