C program stuck on terminal when redirecting its output to another file from bash script

Viewed 540

I am trying to run a C program from a bash file in Linux and then write its output to another file (which is in another directory). The command I am using is:

gcc myfile.c -o test 
./test > /home/"$user"/Documents/"$name"/"$file" 

Whenever I try to run this command, the program doesn't run, rather it is stuck on loading. Even if I write a single file name (from the same directory where the program is), the program does not run until I remove the whole redirection command and just write the simple ./test command. I don't know why this is occurring.

This is the C Program:

#include <stdio.h>

int main()
{
  int array[100], n, c, d, swap;
  printf("Enter number of elements\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
  for (c = 0 ; c < n - 1; c++)
  {
    for (d = 0 ; d < n - c - 1; d++)
    {
      if (array[d] > array[d+1]) 
      {
        swap       = array[d];
        array[d]   = array[d+1];
        array[d+1] = swap;
      }
    }
  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c < n; c++)
     printf("%d\n", array[c]);
  return 0;
}

Even if I'm writing it like this:

./test | tee text.txt

It is not printing anything.

2 Answers

you can use command tee to collect printw info. like ./test | tee file or you try to add 2>&1 in it.

My problem was solved by using the script command in Linux. This command stores and writes both the input and the output that was provided during run-time of the C program into the desired text file. The cat and tee command doesn't work when there is scanf in the C program.

Related