首页 > 解决方案 > C程序在将其输出从bash脚本重定向到另一个文件时卡在终端上

问题描述

我正在尝试从 Linux 中的 bash 文件运行 C 程序,然后将其输出写入另一个文件(位于另一个目录中)。我正在使用的命令是:

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

每当我尝试运行此命令时,程序都不会运行,而是卡在加载中。即使我写了一个文件名(来自程序所在的同一目录),程序也不会运行,直到我删除整个重定向命令并只写简单的 ./test 命令。我不知道为什么会这样。

这是C程序:

#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;
}

即使我这样写:

./test | tee text.txt

它没有打印任何东西。

标签: linuxbashshellubuntu

解决方案


您可以使用命令 tee 来收集 printw 信息。喜欢 ./test | tee 文件,或者您尝试在其中添加 2>&1 。


推荐阅读