c - 运行程序时终端挂起

标签 c linux terminal

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

最佳答案

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

关于c - 运行程序时终端挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21819078/

相关文章:

c - 在 C Caesar Cipher 中使用 ASCII 解密具有未知 key 的打开的文本文件

c++ - 在 C++ 中搜索和替换 C 风格的字符串

c - Strcmp 在相等的字符串上不返回相等

c++ - 在 C/C++ 代码中查找指针是否静态等同于停止问题?

c++ - 使用 C++ 在 Linux 中挂载网络驱动器

linux - 更新Xubuntu依赖

c++ - Qt pro文件的CXXFLAGS修改?

macos - 如何将除一个文件和一个目录之外的所有文件复制到另一个目录

r - 使用opencpu连接云服务器时获取授权签名消息

java - 如何在没有回显连接的情况下编写这个特定命令?