Sort Files
Sort a list of files
- Define sort()
- Function definition
- Segment Source
-
1553: /* Sort NFILES FILES onto OFP. */
1554:
1555: static void
1556: sort (char **files, int nfiles, FILE *ofp)
1557: {
1558: struct buffer buf;
1559: struct lines lines;
1560: struct line *tmp;
1561: int i, ntmp;
1562: FILE *fp, *tfp;
1563: struct tempnode *node;
1564: int n_temp_files = 0;
1565: char **tempfiles;
1566:
1567: initbuf (&buf, sortalloc);
1568: initlines (&lines, sortalloc / linelength + 1,
1569: LINEALLOC / sizeof (struct line));
1570: ntmp = lines.alloc;
1571: tmp = (struct line *) xmalloc (ntmp * sizeof (struct line));
1572:
1573: while (nfiles--)
1574: {
1575: fp = xfopen (*files++, "r");
1576: while (fillbuf (&buf, fp))
1577: {
1578: findlines (&buf, &lines);
1579: if (lines.used > ntmp)
1580: {
1581: while (lines.used > ntmp)
1582: ntmp *= 2;
1583: tmp = (struct line *)
1584: xrealloc ((char *) tmp, ntmp * sizeof (struct line));
1585: }
1586: sortlines (lines.lines, lines.used, tmp);
1587: if (feof (fp) && !nfiles && !n_temp_files && !buf.left)
1588: tfp = ofp;
1589: else
1590: {
1591: ++n_temp_files;
1592: tfp = xtmpfopen (tempname ());
1593: }
1594: for (i = 0; i < lines.used; ++i)
1595: if (!unique || i == 0
1596: || compare (&lines.lines[i], &lines.lines[i - 1]))
1597: {
1598: write_bytes (lines.lines[i].text, lines.lines[i].length, tfp);
1599: putc (eolchar, tfp);
1600: }
1601: if (tfp != ofp)
1602: xfclose (tfp);
1603: }
1604: xfclose (fp);
1605: }
1606:
1607: free (buf.buf);
1608: free ((char *) lines.lines);
1609: free ((char *) tmp);
1610:
1611: if (n_temp_files)
1612: {
1613: tempfiles = (char **) xmalloc (n_temp_files * sizeof (char *));
1614: i = n_temp_files;
1615: for (node = temphead.next; i > 0; node = node->next)
1616: tempfiles[--i] = node->name;
1617: merge (tempfiles, n_temp_files, ofp);
1618: free ((char *) tempfiles);
1619: }
1620: }
1621: