blob: 04f17fe31b47b8b13d94af6f8a9b7a8991f0336e (
plain)
1 ////////////////////////////////////////////////////////////////////////
2 // FILE: file.cpp
3 // AUTHOR: Johannes Winkelmann, jw@tks6.net
4 // COPYRIGHT: (c) 2002 by Johannes Winkelmann
5 // ---------------------------------------------------------------------
6 // This program is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2 of the License, or
9 // (at your option) any later version.
10 ////////////////////////////////////////////////////////////////////////
11
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <cstdio>
16 #include <fnmatch.h>
17 #include <libgen.h>
18 #include <cstring>
19
20 using namespace std;
21
22 #include "stringhelper.h"
23 #include "pg_regex.h"
24
25 namespace File
26 {
27
28 bool fileExists( const string& fileName )
29 {
30 struct stat result;
31 return stat( fileName.c_str(), &result ) == 0;
32
33 }
34
35 bool grep( const string& fileName,
36 const string& pattern,
37 list<string>& result,
38 bool fullPath,
39 bool useRegex)
40 {
41 FILE* fp;
42 fp = fopen( fileName.c_str(), "r" );
43 if ( !fp ) {
44 return false;
45 }
46 const int length = BUFSIZ;
47 char input[length];
48 char* p;
49 char* end;
50 string line;
51 string entry;
52
53 RegEx re(pattern);
54
55 while ( fgets( input, length, fp ) ) {
56 p = strtok( input, "\t" );
57 p = strtok( NULL, "\t" );
58 p = strtok( NULL, "\t" );
59
60 if ( p ) {
61 // prepend slash to string
62 p--;
63 p[0] = '/';
64
65 entry = p;
66 end = strstr(p, "->");
67 if (end) {
68 *end = '\0';
69 }
70 p[strlen(p)-1] = '\0'; // strip newline
71
72 char* name = p;
73 if (!fullPath) {
74 name = basename(p);
75 }
76
77 if (useRegex) {
78 if (re.match(name)) {
79 result.push_back(StringHelper::stripWhiteSpace(entry));
80 }
81 } else {
82 if ( fnmatch(pattern.c_str(), name, FNM_CASEFOLD) == 0 ) {
83 result.push_back( StringHelper::stripWhiteSpace(entry) );
84 }
85 }
86 }
87 }
88
89 fclose( fp );
90 return true;
91 }
92
93 }
|