forked from coreutils/coreutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsplit.c
1526 lines (1262 loc) · 38.8 KB
/
csplit.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* csplit - split a file into sections determined by context lines
Copyright (C) 1991-2020 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* Written by Stuart Kemp, [email protected].
Modified by David MacKenzie, [email protected]. */
#include <config.h>
#include <assert.h>
#include <getopt.h>
#include <sys/types.h>
#include <signal.h>
#include "system.h"
#include <regex.h>
#include "die.h"
#include "error.h"
#include "fd-reopen.h"
#include "quote.h"
#include "safe-read.h"
#include "stdio--.h"
#include "xdectoint.h"
#include "xstrtol.h"
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "csplit"
#define AUTHORS \
proper_name ("Stuart Kemp"), \
proper_name ("David MacKenzie")
/* The default prefix for output file names. */
#define DEFAULT_PREFIX "xx"
/* A compiled pattern arg. */
struct control
{
intmax_t offset; /* Offset from regexp to split at. */
uintmax_t lines_required; /* Number of lines required. */
uintmax_t repeat; /* Repeat count. */
int argnum; /* ARGV index. */
bool repeat_forever; /* True if '*' used as a repeat count. */
bool ignore; /* If true, produce no output (for regexp). */
bool regexpr; /* True if regular expression was used. */
struct re_pattern_buffer re_compiled; /* Compiled regular expression. */
};
/* Initial size of data area in buffers. */
#define START_SIZE 8191
/* Increment size for data area. */
#define INCR_SIZE 2048
/* Number of lines kept in each node in line list. */
#define CTRL_SIZE 80
#ifdef DEBUG
/* Some small values to test the algorithms. */
# define START_SIZE 200
# define INCR_SIZE 10
# define CTRL_SIZE 1
#endif
/* A string with a length count. */
struct cstring
{
size_t len;
char *str;
};
/* Pointers to the beginnings of lines in the buffer area.
These structures are linked together if needed. */
struct line
{
size_t used; /* Number of offsets used in this struct. */
size_t insert_index; /* Next offset to use when inserting line. */
size_t retrieve_index; /* Next index to use when retrieving line. */
struct cstring starts[CTRL_SIZE]; /* Lines in the data area. */
struct line *next; /* Next in linked list. */
};
/* The structure to hold the input lines.
Contains a pointer to the data area and a list containing
pointers to the individual lines. */
struct buffer_record
{
size_t bytes_alloc; /* Size of the buffer area. */
size_t bytes_used; /* Bytes used in the buffer area. */
uintmax_t start_line; /* First line number in this buffer. */
uintmax_t first_available; /* First line that can be retrieved. */
size_t num_lines; /* Number of complete lines in this buffer. */
char *buffer; /* Data area. */
struct line *line_start; /* Head of list of pointers to lines. */
struct line *curr_line; /* The line start record currently in use. */
struct buffer_record *next;
};
static void close_output_file (void);
static void create_output_file (void);
static void delete_all_files (bool);
static void save_line_to_file (const struct cstring *line);
/* Start of buffer list. */
static struct buffer_record *head = NULL;
/* Partially read line. */
static char *hold_area = NULL;
/* Number of bytes in 'hold_area'. */
static size_t hold_count = 0;
/* Number of the last line in the buffers. */
static uintmax_t last_line_number = 0;
/* Number of the line currently being examined. */
static uintmax_t current_line = 0;
/* If true, we have read EOF. */
static bool have_read_eof = false;
/* Name of output files. */
static char *volatile filename_space = NULL;
/* Prefix part of output file names. */
static char const *volatile prefix = NULL;
/* Suffix part of output file names. */
static char *volatile suffix = NULL;
/* Number of digits to use in output file names. */
static int volatile digits = 2;
/* Number of files created so far. */
static unsigned int volatile files_created = 0;
/* Number of bytes written to current file. */
static uintmax_t bytes_written;
/* Output file pointer. */
static FILE *output_stream = NULL;
/* Output file name. */
static char *output_filename = NULL;
/* Perhaps it would be cleaner to pass arg values instead of indexes. */
static char **global_argv;
/* If true, do not print the count of bytes in each output file. */
static bool suppress_count;
/* If true, remove output files on error. */
static bool volatile remove_files;
/* If true, remove all output files which have a zero length. */
static bool elide_empty_files;
/* If true, suppress the lines that match the PATTERN */
static bool suppress_matched;
/* The compiled pattern arguments, which determine how to split
the input file. */
static struct control *controls;
/* Number of elements in 'controls'. */
static size_t control_used;
/* The set of signals that are caught. */
static sigset_t caught_signals;
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
SUPPRESS_MATCHED_OPTION = CHAR_MAX + 1
};
static struct option const longopts[] =
{
{"digits", required_argument, NULL, 'n'},
{"quiet", no_argument, NULL, 'q'},
{"silent", no_argument, NULL, 's'},
{"keep-files", no_argument, NULL, 'k'},
{"elide-empty-files", no_argument, NULL, 'z'},
{"prefix", required_argument, NULL, 'f'},
{"suffix-format", required_argument, NULL, 'b'},
{"suppress-matched", no_argument, NULL, SUPPRESS_MATCHED_OPTION},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
/* Optionally remove files created so far; then exit.
Called when an error detected. */
static void
cleanup (void)
{
sigset_t oldset;
close_output_file ();
sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
delete_all_files (false);
sigprocmask (SIG_SETMASK, &oldset, NULL);
}
static void cleanup_fatal (void) ATTRIBUTE_NORETURN;
static void
cleanup_fatal (void)
{
cleanup ();
exit (EXIT_FAILURE);
}
extern void
xalloc_die (void)
{
error (0, 0, "%s", _("memory exhausted"));
cleanup_fatal ();
}
static void
interrupt_handler (int sig)
{
delete_all_files (true);
signal (sig, SIG_DFL);
/* The signal has been reset to SIG_DFL, but blocked during this
handler. Force the default action of this signal once the
handler returns and the block is removed. */
raise (sig);
}
/* Keep track of NUM bytes of a partial line in buffer START.
These bytes will be retrieved later when another large buffer is read. */
static void
save_to_hold_area (char *start, size_t num)
{
free (hold_area);
hold_area = start;
hold_count = num;
}
/* Read up to MAX_N_BYTES bytes from the input stream into DEST.
Return the number of bytes read. */
static size_t
read_input (char *dest, size_t max_n_bytes)
{
size_t bytes_read;
if (max_n_bytes == 0)
return 0;
bytes_read = safe_read (STDIN_FILENO, dest, max_n_bytes);
if (bytes_read == 0)
have_read_eof = true;
if (bytes_read == SAFE_READ_ERROR)
{
error (0, errno, _("read error"));
cleanup_fatal ();
}
return bytes_read;
}
/* Initialize existing line record P. */
static void
clear_line_control (struct line *p)
{
p->used = 0;
p->insert_index = 0;
p->retrieve_index = 0;
}
/* Return a new, initialized line record. */
static struct line *
new_line_control (void)
{
struct line *p = xmalloc (sizeof *p);
p->next = NULL;
clear_line_control (p);
return p;
}
/* Record LINE_START, which is the address of the start of a line
of length LINE_LEN in the large buffer, in the lines buffer of B. */
static void
keep_new_line (struct buffer_record *b, char *line_start, size_t line_len)
{
struct line *l;
/* If there is no existing area to keep line info, get some. */
if (b->line_start == NULL)
b->line_start = b->curr_line = new_line_control ();
/* If existing area for lines is full, get more. */
if (b->curr_line->used == CTRL_SIZE)
{
b->curr_line->next = new_line_control ();
b->curr_line = b->curr_line->next;
}
l = b->curr_line;
/* Record the start of the line, and update counters. */
l->starts[l->insert_index].str = line_start;
l->starts[l->insert_index].len = line_len;
l->used++;
l->insert_index++;
}
/* Scan the buffer in B for newline characters
and record the line start locations and lengths in B.
Return the number of lines found in this buffer.
There may be an incomplete line at the end of the buffer;
a pointer is kept to this area, which will be used when
the next buffer is filled. */
static size_t
record_line_starts (struct buffer_record *b)
{
char *line_start; /* Start of current line. */
char *line_end; /* End of each line found. */
size_t bytes_left; /* Length of incomplete last line. */
size_t lines; /* Number of lines found. */
size_t line_length; /* Length of each line found. */
if (b->bytes_used == 0)
return 0;
lines = 0;
line_start = b->buffer;
bytes_left = b->bytes_used;
while (true)
{
line_end = memchr (line_start, '\n', bytes_left);
if (line_end == NULL)
break;
line_length = line_end - line_start + 1;
keep_new_line (b, line_start, line_length);
bytes_left -= line_length;
line_start = line_end + 1;
lines++;
}
/* Check for an incomplete last line. */
if (bytes_left)
{
if (have_read_eof)
{
keep_new_line (b, line_start, bytes_left);
lines++;
}
else
save_to_hold_area (xmemdup (line_start, bytes_left), bytes_left);
}
b->num_lines = lines;
b->first_available = b->start_line = last_line_number + 1;
last_line_number += lines;
return lines;
}
/* Return a new buffer with room to store SIZE bytes, plus
an extra byte for safety. */
static struct buffer_record *
create_new_buffer (size_t size)
{
struct buffer_record *new_buffer = xmalloc (sizeof *new_buffer);
new_buffer->buffer = xmalloc (size + 1);
new_buffer->bytes_alloc = size;
new_buffer->line_start = new_buffer->curr_line = NULL;
return new_buffer;
}
/* Return a new buffer of at least MINSIZE bytes. If a buffer of at
least that size is currently free, use it, otherwise create a new one. */
static struct buffer_record *
get_new_buffer (size_t min_size)
{
struct buffer_record *new_buffer; /* Buffer to return. */
size_t alloc_size; /* Actual size that will be requested. */
alloc_size = START_SIZE;
if (alloc_size < min_size)
{
size_t s = min_size - alloc_size + INCR_SIZE - 1;
alloc_size += s - s % INCR_SIZE;
}
new_buffer = create_new_buffer (alloc_size);
new_buffer->num_lines = 0;
new_buffer->bytes_used = 0;
new_buffer->start_line = new_buffer->first_available = last_line_number + 1;
new_buffer->next = NULL;
return new_buffer;
}
static void
free_buffer (struct buffer_record *buf)
{
struct line *l;
for (l = buf->line_start; l;)
{
struct line *n = l->next;
free (l);
l = n;
}
buf->line_start = NULL;
free (buf->buffer);
buf->buffer = NULL;
}
/* Append buffer BUF to the linked list of buffers that contain
some data yet to be processed. */
static void
save_buffer (struct buffer_record *buf)
{
struct buffer_record *p;
buf->next = NULL;
buf->curr_line = buf->line_start;
if (head == NULL)
head = buf;
else
{
for (p = head; p->next; p = p->next)
/* Do nothing. */ ;
p->next = buf;
}
}
/* Fill a buffer of input.
Set the initial size of the buffer to a default.
Fill the buffer (from the hold area and input stream)
and find the individual lines.
If no lines are found (the buffer is too small to hold the next line),
release the current buffer (whose contents would have been put in the
hold area) and repeat the process with another large buffer until at least
one entire line has been read.
Return true if a new buffer was obtained, otherwise false
(in which case end-of-file must have been encountered). */
static bool
load_buffer (void)
{
struct buffer_record *b;
size_t bytes_wanted = START_SIZE; /* Minimum buffer size. */
size_t bytes_avail; /* Size of new buffer created. */
size_t lines_found; /* Number of lines in this new buffer. */
char *p; /* Place to load into buffer. */
if (have_read_eof)
return false;
/* We must make the buffer at least as large as the amount of data
in the partial line left over from the last call. */
if (bytes_wanted < hold_count)
bytes_wanted = hold_count;
while (1)
{
b = get_new_buffer (bytes_wanted);
bytes_avail = b->bytes_alloc; /* Size of buffer returned. */
p = b->buffer;
/* First check the 'holding' area for a partial line. */
if (hold_count)
{
memcpy (p, hold_area, hold_count);
p += hold_count;
b->bytes_used += hold_count;
bytes_avail -= hold_count;
hold_count = 0;
}
b->bytes_used += read_input (p, bytes_avail);
lines_found = record_line_starts (b);
if (lines_found || have_read_eof)
break;
if (xalloc_oversized (2, b->bytes_alloc))
xalloc_die ();
bytes_wanted = 2 * b->bytes_alloc;
free_buffer (b);
free (b);
}
if (lines_found)
save_buffer (b);
else
{
free_buffer (b);
free (b);
}
return lines_found != 0;
}
/* Return the line number of the first line that has not yet been retrieved. */
static uintmax_t
get_first_line_in_buffer (void)
{
if (head == NULL && !load_buffer ())
die (EXIT_FAILURE, errno, _("input disappeared"));
return head->first_available;
}
/* Return a pointer to the logical first line in the buffer and make the
next line the logical first line.
Return NULL if there is no more input. */
static struct cstring *
remove_line (void)
{
/* If non-NULL, this is the buffer for which the previous call
returned the final line. So now, presuming that line has been
processed, we can free the buffer and reset this pointer. */
static struct buffer_record *prev_buf = NULL;
struct cstring *line; /* Return value. */
struct line *l; /* For convenience. */
if (prev_buf)
{
free_buffer (prev_buf);
free (prev_buf);
prev_buf = NULL;
}
if (head == NULL && !load_buffer ())
return NULL;
if (current_line < head->first_available)
current_line = head->first_available;
++(head->first_available);
l = head->curr_line;
line = &l->starts[l->retrieve_index];
/* Advance index to next line. */
if (++l->retrieve_index == l->used)
{
/* Go on to the next line record. */
head->curr_line = l->next;
if (head->curr_line == NULL || head->curr_line->used == 0)
{
/* Go on to the next data block.
but first record the current one so we can free it
once the line we're returning has been processed. */
prev_buf = head;
head = head->next;
}
}
return line;
}
/* Search the buffers for line LINENUM, reading more input if necessary.
Return a pointer to the line, or NULL if it is not found in the file. */
static struct cstring *
find_line (uintmax_t linenum)
{
struct buffer_record *b;
if (head == NULL && !load_buffer ())
return NULL;
if (linenum < head->start_line)
return NULL;
for (b = head;;)
{
assert (b);
if (linenum < b->start_line + b->num_lines)
{
/* The line is in this buffer. */
struct line *l;
size_t offset; /* How far into the buffer the line is. */
l = b->line_start;
offset = linenum - b->start_line;
/* Find the control record. */
while (offset >= CTRL_SIZE)
{
l = l->next;
offset -= CTRL_SIZE;
}
return &l->starts[offset];
}
if (b->next == NULL && !load_buffer ())
return NULL;
b = b->next; /* Try the next data block. */
}
}
/* Return true if at least one more line is available for input. */
static bool
no_more_lines (void)
{
return find_line (current_line + 1) == NULL;
}
/* Open NAME as standard input. */
static void
set_input_file (const char *name)
{
if (! STREQ (name, "-") && fd_reopen (STDIN_FILENO, name, O_RDONLY, 0) < 0)
die (EXIT_FAILURE, errno, _("cannot open %s for reading"),
quoteaf (name));
}
/* Write all lines from the beginning of the buffer up to, but
not including, line LAST_LINE, to the current output file.
If IGNORE is true, do not output lines selected here.
ARGNUM is the index in ARGV of the current pattern. */
static void
write_to_file (uintmax_t last_line, bool ignore, int argnum)
{
struct cstring *line;
uintmax_t first_line; /* First available input line. */
uintmax_t lines; /* Number of lines to output. */
uintmax_t i;
first_line = get_first_line_in_buffer ();
if (first_line > last_line)
{
error (0, 0, _("%s: line number out of range"),
quote (global_argv[argnum]));
cleanup_fatal ();
}
lines = last_line - first_line;
for (i = 0; i < lines; i++)
{
line = remove_line ();
if (line == NULL)
{
error (0, 0, _("%s: line number out of range"),
quote (global_argv[argnum]));
cleanup_fatal ();
}
if (!ignore)
save_line_to_file (line);
}
}
/* Output any lines left after all regexps have been processed. */
static void
dump_rest_of_file (void)
{
struct cstring *line;
while ((line = remove_line ()) != NULL)
save_line_to_file (line);
}
/* Handle an attempt to read beyond EOF under the control of record P,
on iteration REPETITION if nonzero. */
static void handle_line_error (const struct control *, uintmax_t)
ATTRIBUTE_NORETURN;
static void
handle_line_error (const struct control *p, uintmax_t repetition)
{
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
fprintf (stderr, _("%s: %s: line number out of range"),
program_name, quote (umaxtostr (p->lines_required, buf)));
if (repetition)
fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
else
fprintf (stderr, "\n");
cleanup_fatal ();
}
/* Determine the line number that marks the end of this file,
then get those lines and save them to the output file.
P is the control record.
REPETITION is the repetition number. */
static void
process_line_count (const struct control *p, uintmax_t repetition)
{
uintmax_t linenum;
uintmax_t last_line_to_save = p->lines_required * (repetition + 1);
create_output_file ();
/* Ensure that the line number specified is not 1 greater than
the number of lines in the file.
When suppressing matched lines, check before the loop. */
if (no_more_lines () && suppress_matched)
handle_line_error (p, repetition);
linenum = get_first_line_in_buffer ();
while (linenum++ < last_line_to_save)
{
struct cstring *line = remove_line ();
if (line == NULL)
handle_line_error (p, repetition);
save_line_to_file (line);
}
close_output_file ();
if (suppress_matched)
remove_line ();
/* Ensure that the line number specified is not 1 greater than
the number of lines in the file. */
if (no_more_lines () && !suppress_matched)
handle_line_error (p, repetition);
}
static void regexp_error (struct control *, uintmax_t, bool) ATTRIBUTE_NORETURN;
static void
regexp_error (struct control *p, uintmax_t repetition, bool ignore)
{
fprintf (stderr, _("%s: %s: match not found"),
program_name, quote (global_argv[p->argnum]));
if (repetition)
{
char buf[INT_BUFSIZE_BOUND (uintmax_t)];
fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf));
}
else
fprintf (stderr, "\n");
if (!ignore)
{
dump_rest_of_file ();
close_output_file ();
}
cleanup_fatal ();
}
/* Read the input until a line matches the regexp in P, outputting
it unless P->IGNORE is true.
REPETITION is this repeat-count; 0 means the first time. */
static void
process_regexp (struct control *p, uintmax_t repetition)
{
struct cstring *line; /* From input file. */
size_t line_len; /* To make "$" in regexps work. */
uintmax_t break_line; /* First line number of next file. */
bool ignore = p->ignore; /* If true, skip this section. */
regoff_t ret;
if (!ignore)
create_output_file ();
if (suppress_matched && current_line > 0)
remove_line ();
/* If there is no offset for the regular expression, or
it is positive, then it is not necessary to buffer the lines. */
if (p->offset >= 0)
{
while (true)
{
line = find_line (++current_line);
if (line == NULL)
{
if (p->repeat_forever)
{
if (!ignore)
{
dump_rest_of_file ();
close_output_file ();
}
exit (EXIT_SUCCESS);
}
else
regexp_error (p, repetition, ignore);
}
line_len = line->len;
if (line->str[line_len - 1] == '\n')
line_len--;
ret = re_search (&p->re_compiled, line->str, line_len,
0, line_len, NULL);
if (ret == -2)
{
error (0, 0, _("error in regular expression search"));
cleanup_fatal ();
}
if (ret == -1)
{
line = remove_line ();
if (!ignore)
save_line_to_file (line);
}
else
break;
}
}
else
{
/* Buffer the lines. */
while (true)
{
line = find_line (++current_line);
if (line == NULL)
{
if (p->repeat_forever)
{
if (!ignore)
{
dump_rest_of_file ();
close_output_file ();
}
exit (EXIT_SUCCESS);
}
else
regexp_error (p, repetition, ignore);
}
line_len = line->len;
if (line->str[line_len - 1] == '\n')
line_len--;
ret = re_search (&p->re_compiled, line->str, line_len,
0, line_len, NULL);
if (ret == -2)
{
error (0, 0, _("error in regular expression search"));
cleanup_fatal ();
}
if (ret != -1)
break;
}
}
/* Account for any offset from this regexp. */
break_line = current_line + p->offset;
write_to_file (break_line, ignore, p->argnum);
if (!ignore)
close_output_file ();
if (p->offset > 0)
current_line = break_line;
}
/* Split the input file according to the control records we have built. */
static void
split_file (void)
{
for (size_t i = 0; i < control_used; i++)
{
uintmax_t j;
if (controls[i].regexpr)
{
for (j = 0; (controls[i].repeat_forever
|| j <= controls[i].repeat); j++)
process_regexp (&controls[i], j);
}
else
{
for (j = 0; (controls[i].repeat_forever
|| j <= controls[i].repeat); j++)
process_line_count (&controls[i], j);
}
}
create_output_file ();
dump_rest_of_file ();
close_output_file ();
}
/* Return the name of output file number NUM.
This function is called from a signal handler, so it should invoke
only reentrant functions that are async-signal-safe. POSIX does
not guarantee this for the functions called below, but we don't
know of any hosts where this implementation isn't safe. */
static char *
make_filename (unsigned int num)
{
strcpy (filename_space, prefix);
if (suffix)
sprintf (filename_space + strlen (prefix), suffix, num);
else
sprintf (filename_space + strlen (prefix), "%0*u", digits, num);
return filename_space;
}
/* Create the next output file. */
static void
create_output_file (void)
{
bool fopen_ok;
int fopen_errno;
output_filename = make_filename (files_created);
if (files_created == UINT_MAX)
{
fopen_ok = false;
fopen_errno = EOVERFLOW;
}
else
{
/* Create the output file in a critical section, to avoid races. */
sigset_t oldset;
sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
output_stream = fopen (output_filename, "w");
fopen_ok = (output_stream != NULL);
fopen_errno = errno;
files_created += fopen_ok;
sigprocmask (SIG_SETMASK, &oldset, NULL);
}
if (! fopen_ok)
{
error (0, fopen_errno, "%s", quotef (output_filename));
cleanup_fatal ();
}
bytes_written = 0;
}
/* If requested, delete all the files we have created. This function
must be called only from critical sections. */
static void
delete_all_files (bool in_signal_handler)
{
if (! remove_files)
return;
for (unsigned int i = 0; i < files_created; i++)
{
const char *name = make_filename (i);
if (unlink (name) != 0 && !in_signal_handler)
error (0, errno, "%s", quotef (name));
}
files_created = 0;
}
/* Close the current output file and print the count
of characters in this file. */
static void