linux下split命令行实现的源码

更新时间:2023-06-16 06:22:24 阅读: 评论:0

/* split.c -- split a file into pieces.
Copyright (C) 88, 91, 1995-2002 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 Licen as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be uful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public Licen for more details.
You should have received a copy of the GNU General Public Licen
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
/* By tege@sics., with rms.
To do:
* Implement -t CHAR or -t REGEX to specify break characters other
than newline. */
#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>
#include "system.h"
#include "cloout.h"
#include "dirname.h"
#include "error.h"
#include "full-write.h"
#include "posixver.h"
#include "safe-read.h"
#include "xstrtol.h"
/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "split"
#define AUTHORS N_ ("Torbjorn Granlund and Richard M. Stallman")
#define DEFAULT_SUFFIX_LENGTH 2
/
* The name this program was run with. */
char *program_name;
/* Ba name of output files.  */
static char const *outba;
/* Name of output files.  */
static char *outfile;
/* Pointer to the end of the prefix in OUTFILE.
Suffixes are inrted here.  */
static char *outfile_mid;
/* Length of OUTFILE's suffix.  */
static size_t suffix_length = DEFAULT_SUFFIX_LENGTH;
/
* Name of input file.  May be "-".  */
static char *infile;
/* Descriptor on which input file is open.  */
static int input_desc;
/* Descriptor on which output file is open.  */
static int output_desc;
/* If nonzero, print a diagnostic on standard error just before each
output file is opened. */
static int verbo;
static struct option const longopts[] =
{
{"bytes", required_argument, NULL, 'b'},
{"lines", required_argument, NULL, 'l'},
{"line-bytes", required_argument, NULL, 'C'},
{"suffix-length", required_argument, NULL, 'a'},
{"verbo", no_argument, NULL, 2},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
void
usage (int status)
{
if (status != 0)
fprintf (stderr, _("Try `%s --help' for more information.\n"),
program_name);
el
{
printf (_("\
推荐一本好书400字Usage: %s [OPTION] [INPUT [PREFIX]]\n\
"),
program_name);
fputs (_("\
Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\
PREFIX is `x'.  With no INPUT, or when INPUT is -, read standard input.\n\
\n\
"), stdout);
fputs (_("\
Mandatory arguments to
long options are mandatory for short options too.\n\
"), stdout);
fprintf (stdout, _("\
-a, --suffix-length=N  u suffixes of length N (default %d)\n\
-b, --bytes=SIZE        put SIZE bytes per output file\n\
-
C, --line-bytes=SIZE  put at most SIZE bytes of lines per output file\n\
-l, --lines=NUMBER      put NUMBER lines per output file\n\
"), DEFAULT_SUFFIX_LENGTH);
fputs (_("\
--verbo          print a diagnostic to standard error just\n\
before each output file is opened\n\
"), stdout);
fputs (HELP_OPTION_DESCRIPTION, stdout);
fputs (VERSION_OPTION_DESCRIPTION, stdout);
fputs (_("\
\n\
SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.\n\
"), stdout);
printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
}
exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
/* Compute the next quential output file name and store it into the
string `outfile'.  */
static void
next_file_name (void)
{
if (! outfile)
{
/* Allocate and initialize the first file name.  */
size_t outba_length = strlen (outba);
size_t outfile_length = outba_length + suffix_length;
if (outfile_length + 1 < outba_length)
xalloc_die ();
outfile = xmalloc (outfile_length + 1);
outfile_mid = outfile + outba_length;
memcpy (outfile, outba, outba_length);
memt (outfile_mid, 'a', suffix_length);
outfile[outfile_length] = 0;
#if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX
/* POSIX requires that if the output file name is too long for
its directory, `split' must fail without creating any files.
This must be checked for explicitly on operating systems that
silently truncate file names.  */
{
char *dir = dir_name (outfile);
long name_max = pathconf (dir, _PC_NAME_MAX);
if (0 <= name_max && name_max < ba_len (ba_name (outfile)))
error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile);
free (dir);
}
#endif
}
el
{
/* Increment the suffix in place, if possible.  */
char *p;
for (p = outfile_mid + suffix_length; outfile_mid < p; *--p = 'a')
if (p[-1]++ != 'z')
return;
error (EXIT_FAILURE, 0, _("Output file suffixes exhausted"));
}
}
/* Write BYTES bytes at BP to an output file.
If NEW_FILE_FLAG is nonzero, open the next output file.
Otherwi add to the same output file already in u.  */
static void
cwrite (int new_file_flag, const char *bp, int bytes)
{
if (new_file_flag)
{
if (output_desc >= 0 && clo (output_desc) < 0)
error (EXIT_FAILURE, errno, "%s", outfile);
next_file_name ();
if (verbo)
fprintf (stderr, _("creating file `%s'\n"), outfile);
output_desc = open (outfile,
O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
if (output_desc < 0)
error (EXIT_FAILURE, errno, "%s",
outfile);
}
if (full_write (output_desc, bp, bytes) != (size_t) bytes)
error (EXIT_FAILURE, errno, "%s", outfile);
}
/* Read NCHARS bytes from the input file into BUF.
Return the number of bytes successfully read.
If this is less than NCHARS, do not call `stdread' again.  */
static int
stdread (char *buf, int nchars)
{
int n_read;
int to_be_read = nchars;
while (to_be_read)
{
n_read = safe_read (input_desc, buf, to_be_read);
if (n_read < 0)
return -1;
if (n_read == 0)
break;
to_be_read -= n_read;
buf += n_read;
}
return nchars - to_be_read;
}
/* Split into pieces of exactly NCHARS bytes.
U buffer BUF, who size is BUFSIZE.  */
static void
bytes_split (int nchars, char *buf, int bufsize)
{
int n_read;
int new_file_flag = 1;
int to_read;
int to_write = nchars;
char *bp_out;
埃斯泰克的海湾do
{
n_read = stdread (buf, bufsize);
if (n_read < 0)
error (EXIT_FAILURE, errno, "%s", infile);
bp_out = buf;
to_read = n_read;
for (;;)
京东发展历程{
if (to_read < to_write)
{
if (to_read) /* do not write 0 bytes! */
{
cwrite (new_file_flag, bp_out, to_read);
to_write -= to_read;
new_file_flag = 0;
}
break;
}
el
{
cwrite (new_file_flag, bp_out, to_write);
bp_out += to_write;
to_read -= to_write;
new_file_flag = 1;
to_write = nchars;
}
}
}
while (n_read == bufsize);
}
/* Split into pieces of exactly NLINES lines.
U buffer BUF, who size is BUFSIZE.  */
static void
lines_split (int nlines, char *buf, int bufsize)
{
int n_read;
char *bp, *bp_out, *eob;
int new_file_flag = 1;
int n = 0;
do
{
n_read = stdread (buf, bufsize);
if (n_read < 0)
error (EXIT_FAILURE, errno, "%s", infile);
bp = bp_out = buf;
eob = bp + n_read;
*eob = '\n';
for (;;)
{
while (*bp++ != '\n')
;  /* this micolon takes most of the time */
if (bp > eob)
{
if (eob != bp_out) /* do not write 0 bytes! */
{
cwrite (new_file_flag, bp_out, eob - bp_out);
new_file_flag = 0;
}
break;
}
el
if (++n >= nlines)
{
cwrite (new_file_flag, bp_out, bp - bp_out);
bp_out = bp;
new_file_flag = 1;
n = 0;
}
}
}
while (n_read == bufsize);
}
/* Split into pieces that are as large as possible while still not more
than NCHARS bytes, and are split on line boundaries except
where lines longer than NCHARS bytes occur. */
static void
line_bytes_split (int nchars)短语大全
{
int n_read;
char *bp;
int eof = 0;
int n_buffered = 0;
char *buf = (char *) xmalloc (nchars);
do
{
/* Fill up the full buffer size from the input file.  */
n_read = stdread (buf + n_buffered, nchars - n_buffered);
if (n_read < 0)
error
(EXIT_FAILURE, errno, "%s", infile);
n_buffered += n_read;
if (n_buffered != nchars)
eof = 1;
/* Find where to end this chunk.  */
bp = buf + n_buffered;
if (n_buffered == nchars)
{
while (bp > buf && bp[-1] != '\n')
bp--;
}
/* If chunk has no newlines, u all the chunk.  */
if (bp == buf)
bp = buf + n_buffered;
/* Output the chars as one output file.  */
cwrite (1, buf, bp - buf);
/* Discard the chars we just output; move rest of chunk
down to be the start of the next chunk.  Source and
destination probably overlap.  */
n_buffered -= bp - buf;
if (n_buffered > 0)
memmove (buf, bp, n_buffered);
}
while (!eof);
free (buf);
}
#define FAIL_ONLY_ONE_WAY()    \
do        \
{        \
error (0, 0, _("cannot split in more than one way")); \
工作之余usage (EXIT_FAILURE);    \
}        \
while (0)
int
main (int argc, char **argv)
{
struct stat stat_buf;
int num;  /* numeric argument from command line */
enum
{
type_undef, type_bytes, type_byteslines, type_lines, type_digits
} split_type = type_undef;
int in_blk_size;  /* optimal block size of input file device */
char *buf;  /* file i/o buffer */
int accum = 0;
int c;
int digits_optind = 0;
program_name = argv[0];
tlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
atexit (clo_stdout);
/* Par command line options.  */
infile = "-";
outba = "x";
while (1)
{
/* This is the argv-index of the option we will read next.  */
int this_optind = optind ? optind : 1;
long int tmp_long;
c = getopt_long (argc, argv, "0123456789C:a:b:l:", longopts, NULL);
if (c == -1)
break;
switch (c)
{
ca 0:
break;
ca 'a':
{
unsigned long tmp;
if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK
|| SIZE_MAX < tmp)
{
error (0, 0, _("%s: invalid suffix length"), optarg);
usage (EXIT_FAILURE);
}
suffix_length = tmp;
}
break;
ca 'b':
if (split_type != type_undef)
FAIL_ONLY_ONE_WAY ();
split_type = type_bytes;
if (xstrtol (optarg, NULL, 10, &tmp_long, "bkm") != LONGINT_OK
|| tmp_long < 0 || tmp_long > INT_MAX)
{
error (0, 0, _("%s: invalid number of bytes"), optarg);
usage (EXIT_FAILURE);
}
accum = (int) tmp_long;
break;
ca 'l':
if (split_type != type_undef)
FAIL_ONLY_ONE_WAY ();
split_type = type_lines;
if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
|| tmp_long < 0 || tmp_long > INT_MAX)
{
error (0, 0, _("%s: invalid number of lines"), optarg);
usage (EXIT_FAILURE);
}
accum = (int) tmp_long;
break;
ca 'C':
if (split_type != type_undef)
FAIL_ONLY_ONE_WAY ();
split_type =
type_byteslines;
if (xstrtol (optarg, NULL, 10, &tmp_long, "bkm") != LONGINT_OK
|| tmp_long < 0 ||  tmp_long > INT_MAX)
{
error (0, 0, _("%s: invalid number of bytes"), optarg);
usage (EXIT_FAILURE);
}
accum = (int) tmp_long;
break;
ca '0':
ca '1':
ca '2':
ca '3':
ca '4':
ca '5':
ca '6':
ca '7':
ca '8':
ca '9':
if (split_type != type_undef && split_type != type_digits)
无线电基础知识
FAIL_ONLY_ONE_WAY ();
if (digits_optind != 0 && digits_optind != this_optind)
accum = 0;  /* More than one number given; ignore other. */
digits_optind = this_optind;
split_type = type_digits;
咳嗽出血accum = accum * 10 + c - '0';
break;
ca 2:
verbo = 1;
break;
ca_GETOPT_HELP_CHAR;
ca_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
default:
usage (EXIT_FAILURE);
张宗麟
}
}
if (digits_optind && 200112 <= posix2_version ()
&& getenv ("POSIXLY_CORRECT"))
{
error (0, 0, _("`-%d' option is obsolete; u `-l %d'"), accum, accum);
usage (EXIT_FAILURE);
}
/* Handle default ca.  */
if (split_type == type_undef)
{
split_type = type_lines;
accum = 1000;
}
if (accum < 1)
{
error (0, 0, _("invalid number"));
usage (EXIT_FAILURE);
}
num = accum;
/* Get out the filename arguments.  */
if (optind < argc)
infile = argv[optind++];
if (optind < argc)
outba = argv[optind++];
if (optind < argc)
{
error (0, 0, _("too many arguments"));
usage (EXIT_FAILURE);
}
/* Open the input file.  */
if (STREQ (infile, "-"))
input_desc = 0;
el
{
input_desc = open (infile, O_RDONLY);
if (input_desc < 0)
error (EXIT_FAILURE, errno, "%s", infile);
}
/* Binary I/O is safer when bytecounts are ud.  */
SET_BINARY (input_desc);
/* No output file is open now.  */
output_desc = -1;
/* Get the optimal block size of input device and make a buffer.  */
if (fstat (input_desc, &stat_buf) < 0)
error (EXIT_FAILURE, errno, "%s", infile);
in_blk_size = ST_BLKSIZE (stat_buf);
buf = xmalloc (in_blk_size + 1);
switch (split_type)
{
ca type_digits:
ca type_lines:
lines_split (num, buf, in_blk_size);
break;
ca type_bytes:
bytes_split (num, buf, in_blk_size);
break;
ca type_byteslines:
line_bytes_split (num);
break;
default:
abort ();
}
if (clo (input_desc) < 0)
error (EXIT_FAILURE, errno, "%s", infile);
if (output_desc >= 0 && clo (output_desc) < 0)
error (EXIT_FAILURE, errno, "%s", outfile);
exit (EXIT_SUCCESS);
}

本文发布于:2023-06-16 06:22:24,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/1040702.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:发展   推荐   海湾   咳嗽   历程   好书   埃斯
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图