FileUtil.cpp
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007 #include "String.h"
00008 #include <vector>
00009 #include <algorithm>
00010 #include <sys/types.h>
00011 #include <dirent.h>
00012 #include <stdio.h>
00013 #include <iostream>
00014
00015 #include "Destroyer.h"
00016 #include "FileUtil.h"
00017 #include "FileHeader.h"
00018
00019
00020 FileUtil * FileUtil::s_instance = 0;
00021 DestroyerDeclare(FileUtil)
00022
00023
00024 void FileUtil::readDir(std::vector<String> & files,
00025 char * dirName,
00026 char * prefix)
00027 {
00028 int n = 0;
00029 struct dirent *dp;
00030 DIR * dfd = ::opendir(dirName);
00031 int prefix_len = strlen(prefix);
00032 if (dfd != NULL)
00033 {
00034 char path[2048];
00035 while ((dp = ::readdir(dfd)) != NULL)
00036 {
00037 if (strncmp(dp->d_name, prefix, prefix_len) == 0)
00038 {
00039 n++;
00040 strcpy(path, dirName);
00041 strcat(path, "/");
00042 strcat(path, dp->d_name);
00043 String filename(path);
00044 files.push_back(filename);
00045 }
00046 }
00047 ::closedir(dfd);
00048
00049 sort(files.begin(), files.end());
00050 }
00051
00052 if (n == 0)
00053 fprintf(stderr, "WARNING: no files found matching: %s/%s\n", dirName, prefix);
00054 }
00055
00056 FILE * FileUtil::readOpen(String const & fileName, bool isLarge)
00057 {
00058 FILE * fp = NULL;
00059
00060 if (isLarge)
00061 {
00062 int fd = ::open(fileName.c_str(), O_RDONLY|O_LARGEFILE, 0644);
00063 if (fd > 0)
00064 {
00065 fp = ::fdopen(fd, "r");
00066 }
00067 }
00068 else
00069 {
00070 fp = ::fopen(fileName.c_str(), "r");
00071 }
00072
00073 if (fp == NULL)
00074 {
00075 std::cout << "EXCEPTION: problem opening file: " << fileName << std::endl;
00076 exit(1);
00077 }
00078 #ifndef SILENT
00079 else
00080 {
00081 std::cout << "opening file: " << fileName << std::endl;
00082 }
00083 #endif
00084
00085 return fp;
00086 }
00087
00088 FILE * FileUtil::writeOpen(String const & fileName, bool isLarge)
00089 {
00090 FILE * fp = NULL;
00091
00092 if (isLarge)
00093 {
00094 int fd = ::open(fileName.c_str(), O_CREAT|O_TRUNC|O_WRONLY|O_LARGEFILE, 0644);
00095 if (fd > 0)
00096 {
00097 fp = ::fdopen(fd, "w");
00098 }
00099 }
00100 else
00101 {
00102 fp = ::fopen(fileName.c_str(), "w");
00103 }
00104
00105 if (fp == NULL)
00106 {
00107 std::cout << "EXCEPTION: problem opening file: " << fileName << std::endl;
00108 exit(1);
00109 }
00110 #ifndef SILENT
00111 else
00112 {
00113 std::cout << "opening file: " << fileName << std::endl;
00114 }
00115 #endif
00116
00117 return fp;
00118 }
00119
00120 void FileUtil::close(FILE * & fp)
00121 {
00122 if (fp != 0)
00123 {
00124 ::fclose(fp);
00125 fp = 0;
00126 }
00127 }