【问题标题】:Terminal hangs when I run my program运行程序时终端挂起
【发布时间】:2014-02-17 01:04:11
【问题描述】:

在 unix 中编写了一些代码,通过函数计算 argv[1] 中的单词数。结果返回并显示在标准输出上。

当我运行它时,这个过程会继续进行,直到我杀死它。没有错误显示或任何东西?有没有人介意看看。

谢谢

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

//function declaration
int countWords(char []);

int main(int argc, char* argv [])
{
  int words;

  //check 3 entered values
  if (argc != 3)
  {
    write(2,"Please enter 2 values. Seperated by Space \n", 44);
    exit(0);
  }

  words = countWords(argv[1]);
  printf("Words are %i \n", words);
  return 0;
}

//function to count words
int countWords(char a [])
{
  int counter, openStream, oTest;
  char letter;

  openStream = open(a,O_RDONLY);
  if (openStream < 0)
  {
    write(2, "Error opening specified file. \n", 32); 
    exit(1);
  }

  oTest = read(openStream, &letter, 1);
  while (oTest != 0)
  {
    if (oTest == -1)
    {
      write(2, "Error reading file \n",21);
      exit(2);
    } 
    if (oTest == '\n' || oTest == ' ')
    {
      counter++;
    }
  }
  close(openStream);
  return counter;
}

【问题讨论】:

  • 您可能在while(oTest != 0) 遇到了无限循环,因为您从未将值重新分配给oTest
  • 了解如何use the gdb debugger

标签: c linux terminal


【解决方案1】:

当您的输入流中还有剩余内容时,您正在循环,但您从未真正从循环内的输入流中读取,这意味着您的输入流永远不会超过它的第一个字符,并且您的oTest(第一个字符)永远不会改变。

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    相关资源
    最近更新 更多