]>
git.saurik.com Git - apple/icu.git/blob - icuSources/samples/ugrep/ugrep.cpp
1 /**************************************************************************
3 * Copyright (C) 2002-2010, International Business Machines
4 * Corporation and others. All Rights Reserved.
6 ***************************************************************************
10 // ugrep - an ICU sample program illustrating the use of ICU Regular Expressions.
12 // The use of the ICU Regex API all occurs within the main()
13 // function. The rest of the code deals with with opening files,
14 // encoding conversions, printing results, etc.
16 // This is not a full-featured grep program. The command line options
17 // have been kept to a minimum to avoid complicating the sample code.
26 #include "unicode/utypes.h"
27 #include "unicode/ustring.h"
28 #include "unicode/regex.h"
29 #include "unicode/ucnv.h"
30 #include "unicode/uclean.h"
34 // The following variables contain paramters that may be set from the command line.
36 const char *pattern
= NULL
; // The regular expression
37 int firstFileNum
; // argv index of the first file name
38 UBool displayFileName
= FALSE
;
39 UBool displayLineNum
= FALSE
;
43 // Info regarding the file currently being processed
46 int fileLen
; // Length, in UTF-16 Code Units.
48 UChar
*ucharBuf
= 0; // Buffer, holds converted file. (Simple minded program, always reads
49 // the whole file at once.
51 char *charBuf
= 0; // Buffer, for original, unconverted file data.
55 // Info regarding the line currently being processed
57 int lineStart
; // Index of first char of the current line in the file buffer
58 int lineEnd
; // Index of char following the new line sequence for the current line
62 // Converter, used on output to convert Unicode data back to char *
63 // so that it will display in non-Unicode terminal windows.
65 UConverter
*outConverter
= 0;
68 // Function forward declarations
70 void processOptions(int argc
, const char **argv
);
71 void nextLine(int start
);
74 void readFile(const char *name
);
78 //------------------------------------------------------------------------------------------
82 // Structurally, all use of the ICU Regular Expression API is in main(),
83 // and all of the supporting stuff necessary to make a running program, but
84 // not directly related to regular expressions, is factored out into these other
87 //------------------------------------------------------------------------------------------
88 int main(int argc
, const char** argv
) {
89 UBool matchFound
= FALSE
;
92 // Process the commmand line options.
94 processOptions(argc
, argv
);
97 // Create a RegexPattern object from the user supplied pattern string.
99 UErrorCode status
= U_ZERO_ERROR
; // All ICU operations report success or failure
100 // in a status variable.
102 UParseError parseErr
; // In the event of a syntax error in the regex pattern,
103 // this struct will contain the position of the
106 RegexPattern
*rePat
= RegexPattern::compile(pattern
, parseErr
, status
);
107 // Note that C++ is doing an automatic conversion
108 // of the (char *) pattern to a temporary
109 // UnicodeString object.
110 if (U_FAILURE(status
)) {
111 fprintf(stderr
, "ugrep: error in pattern: \"%s\" at position %d\n",
112 u_errorName(status
), parseErr
.offset
);
117 // Create a RegexMatcher from the newly created pattern.
120 RegexMatcher
*matcher
= rePat
->matcher(empty
, status
);
121 if (U_FAILURE(status
)) {
122 fprintf(stderr
, "ugrep: error in creating RegexMatcher: \"%s\"\n",
123 u_errorName(status
));
128 // Loop, processing each of the input files.
130 for (int fileNum
=firstFileNum
; fileNum
< argc
; fileNum
++) {
131 readFile(argv
[fileNum
]);
134 // Loop through the lines of a file, trying to match the regex pattern on each.
136 for (nextLine(0); lineStart
<fileLen
; nextLine(lineEnd
)) {
137 UnicodeString
s(FALSE
, ucharBuf
+lineStart
, lineEnd
-lineStart
);
139 if (matcher
->find()) {
153 ucnv_close(outConverter
);
155 u_cleanup(); // shut down ICU, release any cached data it owns.
157 return matchFound
? 0: 1;
162 //------------------------------------------------------------------------------------------
164 // doOptions Run through the command line options, and set
165 // the global variables accordingly.
167 // exit without returning if an error occured and
168 // ugrep should not proceed further.
170 //------------------------------------------------------------------------------------------
171 void processOptions(int argc
, const char **argv
) {
173 UBool doUsage
= FALSE
;
174 UBool doVersion
= FALSE
;
178 for(optInd
= 1; optInd
< argc
; ++optInd
) {
182 if(strcmp(arg
, "-V") == 0 || strcmp(arg
, "--version") == 0) {
186 else if(strcmp(arg
, "--help") == 0) {
189 else if(strcmp(arg
, "-n") == 0 || strcmp(arg
, "--line-number") == 0) {
190 displayLineNum
= TRUE
;
192 /* POSIX.1 says all arguments after -- are not options */
193 else if(strcmp(arg
, "--") == 0) {
198 /* unrecognized option */
199 else if(strncmp(arg
, "-", strlen("-")) == 0) {
200 printf("ugrep: invalid option -- %s\n", arg
+1);
203 /* done with options */
215 printf("ugrep version 0.01\n");
216 if (optInd
== argc
) {
221 int remainingArgs
= argc
-optInd
; // pattern file ...
222 if (remainingArgs
< 2) {
223 fprintf(stderr
, "ugrep: files or pattern are missing.\n");
228 if (remainingArgs
> 2) {
229 // More than one file to be processed. Display file names with match output.
230 displayFileName
= TRUE
;
233 pattern
= argv
[optInd
];
234 firstFileNum
= optInd
+1;
237 //------------------------------------------------------------------------------------------
241 //------------------------------------------------------------------------------------------
243 printf("ugrep [options] pattern file...\n"
244 " -V or --version display version information\n"
245 " --help display this help and exit\n"
246 " -- stop further option processing\n"
247 "-n, --line-number Prefix each line of output with the line number within its input file.\n"
252 //------------------------------------------------------------------------------------------
254 // readFile Read a file into memory, and convert it to Unicode.
256 // Since this is just a demo program, take the simple minded approach
257 // of always reading the whole file at once. No intelligent buffering
260 //------------------------------------------------------------------------------------------
261 void readFile(const char *name
) {
264 // Initialize global file variables
267 fileLen
= 0; // zero length prevents processing in case of errors.
271 // Open the file and determine its size.
273 FILE *file
= fopen(name
, "rb");
275 fprintf(stderr
, "ugrep: Could not open file \"%s\"\n", fileName
);
278 fseek(file
, 0, SEEK_END
);
279 int rawFileLen
= ftell(file
);
280 fseek(file
, 0, SEEK_SET
);
286 charBuf
= (char *)realloc(charBuf
, rawFileLen
+1); // Need error checking...
287 int t
= fread(charBuf
, 1, rawFileLen
, file
);
288 if (t
!= rawFileLen
) {
289 fprintf(stderr
, "Error reading file \"%s\"\n", fileName
);
293 charBuf
[rawFileLen
]=0;
297 // Look for a Unicode Signature (BOM) in the data
299 int32_t signatureLength
;
300 const char * charDataStart
= charBuf
;
301 UErrorCode status
= U_ZERO_ERROR
;
302 const char* encoding
= ucnv_detectUnicodeSignature(
303 charDataStart
, rawFileLen
, &signatureLength
, &status
);
304 if (U_FAILURE(status
)) {
305 fprintf(stderr
, "ugrep: ICU Error \"%s\" from ucnv_detectUnicodeSignature()\n",
306 u_errorName(status
));
310 charDataStart
+= signatureLength
;
311 rawFileLen
-= signatureLength
;
315 // Open a converter to take the file to UTF-16
318 conv
= ucnv_open(encoding
, &status
);
319 if (U_FAILURE(status
)) {
320 fprintf(stderr
, "ugrep: ICU Error \"%s\" from ucnv_open()\n", u_errorName(status
));
325 // Convert the file data to UChar.
326 // Preflight first to determine required buffer size.
328 uint32_t destCap
= ucnv_toUChars(conv
,
334 if (status
!= U_BUFFER_OVERFLOW_ERROR
) {
335 fprintf(stderr
, "ugrep: ucnv_toUChars: ICU Error \"%s\"\n", u_errorName(status
));
339 status
= U_ZERO_ERROR
;
340 ucharBuf
= (UChar
*)realloc(ucharBuf
, (destCap
+1) * sizeof(UChar
));
347 if (U_FAILURE(status
)) {
348 fprintf(stderr
, "ugrep: ucnv_toUChars: ICU Error \"%s\"\n", u_errorName(status
));
354 // Successful conversion. Set the global size variables so that
355 // the rest of the processing will proceed for this file.
364 //------------------------------------------------------------------------------------------
366 // nextLine Advance the line index variables, starting at the
367 // specified position in the input file buffer, by
368 // scanning forwrd until the next end-of-line.
370 // Need to take into account all of the possible Unicode
371 // line ending sequences.
373 //------------------------------------------------------------------------------------------
374 void nextLine(int startPos
) {
380 lineStart
= lineEnd
= startPos
;
383 if (lineEnd
>= fileLen
) {
386 UChar c
= ucharBuf
[lineEnd
];
388 if (c
== 0x0a || // Line Feed
389 c
== 0x0c || // Form Feed
390 c
== 0x0d || // Carriage Return
391 c
== 0x85 || // Next Line
392 c
== 0x2028 || // Line Separator
393 c
== 0x2029) // Paragraph separator
399 // Check for CR/LF sequence, and advance over the LF if we're in the middle of one.
400 if (lineEnd
< fileLen
&&
401 ucharBuf
[lineEnd
-1] == 0x0d &&
402 ucharBuf
[lineEnd
] == 0x0a)
409 //------------------------------------------------------------------------------------------
411 // printMatch Called when a matching line has been located.
412 // Print out the line from the file with the match, after
413 // converting it back to the default code page.
415 //------------------------------------------------------------------------------------------
418 UErrorCode status
= U_ZERO_ERROR
;
420 // If we haven't already created a converter for output, do it now.
421 if (outConverter
== 0) {
422 outConverter
= ucnv_open(NULL
, &status
);
423 if (U_FAILURE(status
)) {
424 fprintf(stderr
, "ugrep: Error opening default converter: \"%s\"\n",
425 u_errorName(status
));
430 // Convert the line to be printed back to the default 8 bit code page.
431 // If the line is too long for our buffer, just truncate it.
432 ucnv_fromUChars(outConverter
,
433 buf
, // destination buffer for conversion
434 sizeof(buf
), // capacity of destination buffer
435 &ucharBuf
[lineStart
], // Input to conversion
436 lineEnd
-lineStart
, // number of UChars to convert
438 buf
[sizeof(buf
)-1] = 0; // Add null for use in case of too long lines.
439 // The converter null-terminates its output unless
440 // the buffer completely fills.
442 if (displayFileName
) {
443 printf("%s:", fileName
);
445 if (displayLineNum
) {
446 printf("%d:", lineNum
);