代码之家  ›  专栏  ›  技术社区  ›  DV.

使用stdio在Linux中读取和排序管道数据

c
  •  3
  • DV.  · 技术社区  · 17 年前

    正如标题所说,我需要编写一个小程序来从标准输入中读取数据,对其进行排序,然后将其发送到标准输出。程序应该接受一个参数,告诉它一条记录有多长(以字节为单位)。以下是我测试它的方法:

    printf 'D\x00C\x00\x00B\x00A' | ./binsort 2 | od -c
    

    上面应该输出如下内容:

    0000000  \0   A  \0   B   C  \0   D  \0
    0000010
    

    这是我到目前为止所拥有的( binsort.c ):

    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    
    using namespace std;
    
    
    void print_usage()
    {
            printf("%s\n", "Usage: ");
    }
    
    
    int compare (const void * a, const void * b) // the compare function for qsort... might need some work
    {
      return ( *(int*)a - *(int*)b );
    }
    
    
    int main(int argc, char *argv[])
    {
            if (argc != 2 || stdin == NULL) // check for argument and piped input
            {
                    print_usage();
                    exit(EXIT_FAILURE);
            }
    
            int entry_size = atoi(argv[1]);
    
            if (entry_size <= 0 || entry_size >= INT_MAX) // check for valid range of entry size
            {
                    print_usage();
                    exit(EXIT_FAILURE);
            }
    
            char *input = new char[entry_size]; // to hold single record
    
            while (fgets(input, entry_size, stdin) != NULL)
            {
                    printf("%s", input); // output single record we just read
            }
    
            exit(EXIT_SUCCESS);
    }
    

    然后用编译 g++ binsort.c -o binsort .

    上面编译但不输出 printf 发送给它。它应该以2字节块的形式输出…喜欢 D\0 C\0 \0B \0A …但事实并非如此。

    我想用 qsort 在 malloc/realloc -分配的数组。然而,我从未有过这些经验,事实上,我的头撞在这个小实用程序的几天。有人能帮忙吗?

    P.S.人们问这是否是家庭作业…不是-我公司的开发人员想用它来调试他们项目的输出。

    6 回复  |  直到 10 年前
        1
  •  5
  •   Adam Rosenfield    17 年前

    不要使用 scanf() 和 printf() . 这些应该与文本数据一起使用。因为您处理的是二进制数据,所以您希望使用较低的级别 fread() 和 fwrite() 功能。由于您不知道总共有多少数据,因此必须使用动态数据结构(例如可调整大小的数组)来存储输入。你不能在线处理数据——你必须把它全部读进去,排序,然后写出来。您的排序函数也是错误的——您只比较每个记录的前4个字节,如果记录大小不是4个字节,这是错误的。使用 memcmp() 相反。

    这应该有效:

    char *input = NULL;
    size_t input_size = 0;
    int num_items = 0;
    int entry_size;
    
    int compare_func(const void *e1, const void *e2)
    {
      return memcmp(e1, e2, entry_size);
    }
    
    int main(int argc, char **argv)
    {
       // ...
      char *datum = malloc(entry_size);  // check for NULL
      input_size = 4096;
      input = malloc(input_size);  // check for NULL
    
      while(1)
      {
        if(fread(datum, 1, entry_size, stdin) < entry_size)
          break;
        size_t new_size = (num_items + 1) * entry_size;
        if(new_size > input_size)
        {
          input = realloc(input, input_size * 2);  // check for NULL
          input_size *= 2;
        }
        memcpy(input + num_items * entry_size, datum, entry_size);
        num_items++;
      }
    
      qsort(input, num_items, entry_size, compare_func);
    
      fwrite(input, entry_size, num_items, stdout);
    
      return 0;
    }
    
        2
  •  3
  •   Mr.Ree    17 年前

    P.S.人们问这是否是家庭作业…不是-我公司的开发人员想用它来调试他们项目的输出。

    如果不是家庭作业,这是在Linux下,为什么不使用包含的 “排序” 程序?

    例如。:

    % printf 'D\x00C\x00\x00B\x00A' | sort -z | od -c
    0000000  \0   A  \0   B  \0   C  \0   D  \0
    0000011
    

    fsf/gnu-sort提供-z选项:

    -z, --zero-terminated
            end lines with 0 byte, not newline
    


    修正后补充:

    好吧,看看你怎么还想要自己的代码…

    看看其他人怎么还没有发布一个基于STL的方法。

    注意使用struct函数进行比较(通过stl::sort())。而且,如果您愿意,您可以始终使用ostream_迭代器<string>(cout,“\n”),而不是使事物更具人类可读性。

    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    
    using namespace std;
    
       /* ifstream won't set EOF-state until we try to read past the end-of-file.*/
       /* (Makes for lots of grief trying to read in files...)                   */
    inline bool
    IsStreamStillGood( istream & theStream )
    {
      return theStream && (theStream . peek() != EOF);
    }
    
    template<class TYPE> inline void DELETE( TYPE * x)
    {
      delete x;
      x = (TYPE *) NULL;
    }
    
    struct FUNCTOR
    {
      bool operator()(const string & x, const string & y) { return x < y; }
    };
    
    
    int
    main(int argc, char **argv)
    {
      istream *       stream;
      vector<string>  v;
    
      UASSERT( argc, >, 1 );
    
      const int recordSize = atoi( argv[1] );
      char      buffer [ recordSize + 1 ];
    
      UASSERT( recordSize, >, 0 );
    
    
      if ( argc > 2 )
        stream = new ifstream( argv[2] );
      else
        stream = & cin;
    
    
      while ( IsStreamStillGood( * stream ) )
      {
        stream-> read( buffer, recordSize );
        v.push_back( string( buffer, stream->gcount() ) );
      }
    
      UASSERT( v.back().size(), ==, size_t(recordSize) );
    
    
      FUNCTOR functor;
      sort( v.begin(), v.end(), functor );
    
      copy( v.begin(), v.end(), ostream_iterator<string>(cout) );
    
    
      if ( argc > 2 )
        DELETE(stream);
    }
    


    (再次)修改为:

    关于在STL方法中使用字符串的问题:由于输入中可能有空字符(“\0”),字符串不会因此而混淆吗?有人建议使用char[],但我怀疑会出现同样的问题。

    如果我有 Car〔10〕; 我可以说 C〔0〕=‘0’; . 同样 C〔1〕 或 C〔9〕 . 该数组中可以有任意多个空字符。(当然,取决于数组的大小。)

    现在,当使用 C 作为C字符串,问题是它有多长。是1个字符长还是9个字符长?通常,在C语言中,这取决于第一个空字符出现的位置。

    这样的事情 PrimTf(%s) , SCANF(%s) , STRNCAT() , StncPy() , STRNCPP() 对于嵌入在二进制数据数组中的空字符(“\0”),ETC不太满意。

    但是C++ STD::字符串 独立跟踪长度。至少看起来是这样的,而且它允许: myString.append(10,'\0');

    因此,通过使用 流->读取(缓冲区,记录大小) 我们读取一组字符(字节)。我们真的不在乎它们是否为空(“\0”)。一切都很好。只需给我记录大小的字节数。

    通过创建 v.向后推(字符串(buffer,stream->gcount()) ,我们将一个包含 流->gCount()) 字符(字节)。同样,我们不关心它们是否为空(“\0”)。我们只需要所有 流->gCount()) 字节。

    sort使用functor,该函数使用运算符<(const string&,const string&),该函数使用string::compare(),它将再次使用字符串的长度,并且不关心字符串中实际包含的数据。空值(“\0”)很好。

    现在,如果我们尝试使用v.back().c_str(),那么我们就没有长度了,所以空值会使我们混淆。但只要我们使用同时包含数据和长度的字符串对象(例如v.back()),我们就很好了。

    这就带来了产出。我们再次输出的是字符串,而不是myString.c_str(),所以字符串中的所有字符都会被打印出来。包含空值(“\0”)。

        3
  •  2
  •   jakber    17 年前

    fgets和fprintf处理字符串(在c中是以特殊字符\0结尾的字符数组)。

    对二进制数据使用fread和fwrite。qsort很好,除了您的compare函数需要逐字节比较entry的字节大小,而不仅仅是从void强制转换为int,这是不安全的,可能不正确。

        4
  •  2
  •   Quassnoi    17 年前

    printf 解释 \0 在流中作为终止字符。

    使用 read() 和 write() 而是:

        int res;
        int count;
        while (1) {
                count = 0;
                while(count < entry_size) {
                        res = read(STDIN_FILENO, input + count, entry_size - count);
                        if (res <= 0)
                                exit(errno);
                        count += res;
                }
                count = 0;
                while(res) {
                        res = write(STDOUT_FILENO, input + count, entry_size - count);
                        if (res < 0)
                                exit(errno);
                        count += res;
                }
        }
    
        5
  •  2
  •   dmckee --- ex-moderator kitten    17 年前

    一些可能有帮助的观点(我假设这是家庭作业,所以这有一个教学结构):

    • 在积累数据的时候,你需要把数据放在某个地方。既然你不知道会有多少,动态分配将是必要的。这里有很多选择:动态数组、链接列表、哈希表等。 令人作呕的 …选择一个适合你的(见下文)。

    • 一旦你得到了它,你就需要把它分类。 或 ,您可以首先存储排序后的内容。你知道一个可以管理它的数据结构吗?

    • 一旦它被分类,你只需把它从另一端吐出来。

    容易,不是吗?


    关于评论:

    • 你有K&R吗?或其他一些基本文本 c 或 c++ ?你要一个。你想选择一种或另一种语言并坚持下去。如果您习惯在另一个上下文中进行OO编程,请使用 C++ . 如果你也不知道,用 C++ .

    • 如果您使用C++,STL容器将为您处理动态存储。最简单的方法是使用 std::vector<char[2]> (使用命令行参数中的大小),并调用 <algorithm> 对它排序。

    • 其他人已经指出你需要做二进制IO。这很重要,因为输入和输出的结构都不像文本IO。

        6
  •  1
  •   DV.    17 年前

    感谢大家提出的宝贵建议!只是为了记录,这里已经完成了 binsort.c 这符合预期。

    #include <stdio.h>
    #include <stdlib.h>
    #include <cstring>
    #include <limits.h>
    
    using namespace std;
    
    
    int num_items = 0;
    size_t input_size = 0;
    int entry_size = 0;
    
    
    void print_usage()
    {
            printf("%s\n", "Usage: <binary data> | ./binsort [RECORD_LENGTH]");
            printf("%s\n", "For example: printf 'D\\x00C\\x00\\x00B\\x00A' | ./binsort 2 | od -c");
    }
    
    
    int compare (const void * a, const void * b)
    {
            return memcmp(a, b, entry_size);
    }
    
    
    int main(int argc, char *argv[])
    {
            if (argc != 2 || stdin == NULL)
            {
                    print_usage();
                    exit(EXIT_FAILURE);
            }
    
            entry_size = atoi(argv[1]);
    
            if (entry_size <= 0 || entry_size >= INT_MAX)
            {
                    print_usage();
                    exit(EXIT_FAILURE);
            }
    
            char *input = NULL;
            char *datum = (char*) malloc(entry_size);
            if (datum == NULL)
                    exit(EXIT_FAILURE);
    
            while(1)
            {
                    int read_size = fread(datum, 1, entry_size, stdin);
    
                    if (read_size == 0)
                            break;
    
                    if(read_size < entry_size)
                    {
                            while(read_size < entry_size)
                            {
                                    memcpy(datum, '\0', 1);
                                    read_size++;
                            }
                            break;
                    }
    
                    size_t new_size = (num_items + 1) * entry_size;
                    if(new_size > input_size)
                    {
                            input = (char*) realloc(input, new_size);
                            if (input == NULL)
                                    exit(EXIT_FAILURE);
                            input_size = new_size;
                    }
                    memcpy(input + num_items * entry_size, datum, entry_size);
                    num_items++;
            }
    
            qsort(input, num_items, entry_size, compare);
    
            fwrite(input, entry_size, num_items, stdout);
    
            exit(EXIT_SUCCESS);
    }