Ошибка в C программе, которая воспроизводит функциональность linux commnad - PullRequest
0 голосов
/ 22 апреля 2020

У меня есть следующий код, который в основном воспроизводит функциональность команды w c в linux. Проблема заключается в том, что для двоичных файлов, которые содержат коды ASCII от 0x00 до 0x0F, скрипт неправильно отображает размеры файла. Для обычных недвоичных файлов программа рассчитывает и отображает размеры в порядке. Скрипт, который я использую:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

#define LUNG_BUF 4096

int main(int argc, char** argv)
{
  int bytes = 0;
  int words = 0;
  int newLine = 0;
  int max_value;  // the maximum of the above three
  int dim;        // string width of the max value

  char buffer[LUNG_BUF];
  enum states { WHITESPACE, WORD };
  int state = WHITESPACE;
  if ( argc !=2 )
  {
    printf( "Nu ati introdu snumele  fisierului\n%s", argv[0]);
  }
  else
  {
    int file = open(argv[1], O_RDONLY);

    if(file < 0)
    {
      printf("can not open :%s\n",argv[1]);
    }
    else
    {
      char *thefile = argv[1];
      size_t n;

      while ((n = read(file, buffer, LUNG_BUF - 1)) > 0)
      {
        buffer[n] = '\0';
        char *ptr = buffer;

        while (*ptr)
        {
          bytes++;
          if (*ptr == ' ' || *ptr == '\t')
          {
            state = WHITESPACE;
          }
          else if (*ptr == '\n')
          {
            newLine++;
            state = WHITESPACE;
          }
          else
          {
            if (state == WHITESPACE)
            {
                words++;
            }
            state = WORD;
          }
          ptr++;
        }
      }

      // find out the largest value of all and determine the printed width of it
      max_value = newLine;
      if (words > max_value)
        max_value = words;
      if (bytes > max_value)
        max_value = bytes;
      dim = snprintf(NULL, 0, "%d", max_value);

      // print lines, words, bytes and filename aligned to the longest number
      printf("%*d %*d %*d %s\n", dim, newLine, dim, words, dim, bytes, thefile);
    }
  }
}
...