Xmipp  v3.23.11-Nereus
xmipp_filename.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  * Authors: Carlos Oscar S. Sorzano (coss@cnb.csic.es)
3  *
4  *
5  * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20  * 02111-1307 USA
21  *
22  * All comments concerning this program package may be sent to the
23  * e-mail address 'xmipp@cnb.csic.es'
24  ***************************************************************************/
25 
26 #include <algorithm>
27 #include <dirent.h>
28 #include <fstream>
29 #include <stdio.h>
30 #include <unistd.h>
31 #include "xmipp_filename.h"
32 #include "xmipp_funcs.h"
33 #include "xmipp_image_macros.h"
34 #include "xmipp_image_generic.h"
35 
36 #include <sys/stat.h>
37 
38 
40 
42 {
43  FileNameVersion=version;
44 }
45 
47 {
48  return FileNameVersion;
49 }
50 
51 // Constructor with root, number and extension .............................
52 void FileName::compose(const String &str, size_t no, const String &ext)
53 {
54 
55  if (no == ALL_IMAGES || no == (size_t) -1)
56  REPORT_ERROR(ERR_DEBUG_TEST, "Don't compose with 0 or -1 index, now images index start at 1");
57 
58  *this = (FileName) str;
59 
60  if (no != ALL_IMAGES)
61  this->append(formatString("%06lu", no));
62 
63  if (!ext.empty())
64  *this += (String) "." + ext;
65 }
66 
67 // Constructor: prefix number and filename, mainly for selfiles..
68 void FileName::compose(size_t no, const String &str)
69 {
70  if (no == ALL_IMAGES || no == (size_t) -1)
71  REPORT_ERROR(ERR_DEBUG_TEST, "Don't compose with 0 or -1 index, now images index start at 1");
72 
73  if (no != ALL_IMAGES)
74  {
75  size_t first = str.rfind(AT);
76  if (first != npos)
77  {
78  std::vector<String> prefixes;
79  int nPref = splitString(str.substr(0, first),",",prefixes, false);
80 
81  if (isalpha(prefixes[nPref-1].at(0)))
82  formatStringFast(*this, "%06lu,%s", no, str.c_str());
83  }
84  else
85  formatStringFast(*this, "%06lu@%s", no, str.c_str());
86  }
87  else
88  *this = str;
89 }
90 
91 // Constructor: prefix number, filename root and extension, mainly for selfiles..
92 void FileName::compose(size_t no, const String &str, const String &ext)
93 {
94  if (no == ALL_IMAGES || no == (size_t) -1)
95  REPORT_ERROR(ERR_DEBUG_TEST, "Don't compose with 0 or -1 index, now images index start at 1");
96 
97  if (no != ALL_IMAGES)
98  formatStringFast(*this, "%06lu@%s.%s", no,
99  str.c_str(), ext.c_str());
100  else
101  *this = str;
102 }
103 
104 // Constructor: string and filename, mainly for metadata blocks..
105 void FileName::compose(const String &blockName, const String &str)
106 {
107  if (blockName.empty())
108  *this = str;
109  else
110  formatStringFast(*this, "%s@%s", blockName.c_str(), str.c_str());
111 }
112 
113 // Constructor: string, number and filename, mainly for numered metadata blocks..
114 void FileName::composeBlock(const String &blockName, size_t no, const String &root, const String &ext)
115 {
116  formatStringFast(*this, "%s%06lu@%s", blockName.c_str(), no, root.c_str());
117  if (ext != "")
118  *this += (String) "." + ext;
119 }
120 
121 // Is in stack ............................................................
123 {
124  return find(AT) != String::npos;
125 }
126 
127 // Decompose ..............................................................
128 void FileName::decompose(size_t &no, String &str) const
129 {
130  char buffer[1024];
131  unsigned long int auxNo;
132  int ok = sscanf(c_str(), "%lu@%s", &auxNo, buffer);
133  no=auxNo;
134  if (ok != 2)
135  {
136  no = ALL_IMAGES;
137  str = *this;
138  return;
139  }
140  else if (no == 0)
141  REPORT_ERROR(ERR_INDEX_OUTOFBOUNDS, formatString("FileName::decompose: Incorrect index number at filename %s; It must start at %lu",c_str(),FIRST_IMAGE));
142 
143  str = buffer;
144 }
145 
146 // Get decomposed filename .......................................
148 {
149  String str;
150  size_t no;
151  decompose(no, str);
152  return str;
153 }
154 
155 // Get the root name of a filename .........................................
156 // TODO: Check if it is really needed
158 {
159  size_t skip_directories = find_last_of("/") + 1;
160  size_t point = find_first_of(".", skip_directories);
161  if (point == npos)
162  point = length();
163  size_t root_end = find_last_not_of("0123456789", point - 1);
164  if (root_end + 1 != point)
165  if (point - root_end > FILENAMENUMBERLENGTH)
166  root_end = point - FILENAMENUMBERLENGTH - 1;
167  return substr(0, root_end + 1);
168 }
169 
170 // Convert to lower case characters .........................................
172 {
173  FileName result = *this;
174  for (size_t i = 0; i < result.length(); i++)
175  result[i] = tolower(result[i]);
176  return result;
177 }
178 
179 // Convert to upper case characters .........................................
181 {
182  FileName result = *this;
183  for (size_t i = 0; i < result.length(); i++)
184  result[i] = toupper(result[i]);
185  return result;
186 }
187 
188 // Is substring present?
189 bool FileName::contains(const String& str) const
190 {
191  return find(str) != npos;
192 }
193 
194 // Get substring before first instance of str
195 //TODO: Check behaviour
197 {
198  size_t point = find_first_of(str);
199  return (point != npos ? (FileName)substr(0, point) : *this);
200 }
201 
202 // Get substring before last instance of str
203 //TODO: Check behaviour
205 {
206  size_t point = find_last_of(str);
207  return point != npos ? (FileName)substr(0, point) : *this;
208 }
209 
210 // Get substring after first instance of str
211 //TODO: Check behaviour
213 {
214  size_t point = find_first_of(str);
215  return point != npos ? (FileName)substr(point + 1) : *this;
216 }
217 
218 // Get substring after last instance of str
219 //TODO: Check behaviour
221 {
222  size_t point = find_last_of(str);
223  return point != npos ? (FileName)substr(point + 1) : *this;
224 }
225 
226 // Get the base name of a filename .........................................
228 {
229  FileName baseName = removeLastExtension();
230  return baseName.afterLastOf("/");
231 }
232 
233 
234 // Get the dir of a filename .........................................
236 {
237  size_t pos = find_last_of("/");
238  return (FileName)( pos != npos ? substr(0, pos+1) : "");
239 }
240 
241 // Get the extension of a filename .........................................
243 {
244  size_t posA = find_last_of("/");
245  size_t posB = find_last_of(".");
246  if (posB==npos)
247  return "";
248  if (posA==npos)
249  return substr(posB+1);
250  if (posB>posA)
251  return substr(posB+1);
252  return "";
253 }
254 
255 // Has image extension .....................................................
257 {
258  String ext = getFileFormat();
259  return (ext=="img" || ext=="hed" || ext=="inf" || ext=="raw" || ext=="mrc" ||
260  ext=="map" || ext=="spi" || ext=="xmp" || ext=="tif" || ext=="dm3" ||
261  ext=="spe" || ext=="em" || ext=="pif" || ext=="ser" || ext=="stk" ||
262  ext=="mrcs"|| ext=="jpg" || ext=="dm4");
263 }
264 
265 // Has image extension .....................................................
267 {
268  String ext = getFileFormat();
269  return (ext=="stk" || ext=="spi" || ext=="xmp" || ext=="mrcs" || ext=="mrc" ||
270  ext=="img" || ext=="hed" || ext=="pif" || ext=="tif" || ext=="dm3" ||
271  ext=="ser" || ext=="st" || ext=="dm4");
272 }
273 
274 // Has image extension .....................................................
276 {
277  String ext = getFileFormat();
278  return (ext=="vol" || ext=="spi" || ext=="xmp" || ext=="mrc" || ext=="map" ||
279  ext=="em" || ext=="pif" || ext=="inf" || ext=="raw");
280 }
281 
282 // Has image extension .....................................................
284 {
285  String ext = getFileFormat();
286  return (ext == "sel" || ext == "xmd" || ext == "doc" ||
287  ext == "ctfdat" || ext == "ctfparam" || ext == "pos" ||
288  ext == "sqlite" || ext == "xml" || ext == "star");
289 }
290 
291 // Init random .............................................................
293 {
295  *this = "";
296  for (int i = 0; i < length; i++)
297  *this += 'a' + FLOOR(rnd_unif(0, 26));
298 }
299 
300 // Init Unique .............................................................
301 void FileName::initUniqueName(const char *templateStr, const String &fnDir)
302 {
303 #ifndef __MINGW32__
304  int fd;
305  const int len=512;
306  char filename[len];
307  if (fnDir!="")
308  strcpy(filename,(fnDir+"/").c_str());
309  else
310  filename[0]=0;
311  strcat(filename, templateStr);
312  filename[len - 1] = 0;
313  if ((fd = mkstemp(filename)) == -1)
314  {
315  perror("FileName::Error generating tmp lock file");
316  exit(1);
317  }
318  close(fd);
319  *this = filename;
320 #endif
321 }
322 
323 // Add at beginning ........................................................
324 FileName FileName::addPrefix(const String &prefix) const
325 {
326  FileName retval = *this;
327  int skip_directories = find_last_of("/") + 1;
328  return retval.insert(skip_directories, prefix);
329 }
330 
331 // Add at the end ..........................................................
333 {
334  if (ext == "")
335  return *this;
336  else
337  {
338  FileName retval = *this;
339  retval = retval.append((String) "." + ext);
340  return retval;
341  }
342 }
343 
344 // Remove last extension ...................................................
346 {
347  FileName retval = *this;
348  return retval.substr(0, rfind("."));
349 }
350 
351 // Remove root .............................................................
353 {
354  return removeSubstring(getRoot());
355 }
356 
357 // Insert before extension .................................................
359 {
360  FileName retval = *this;
361  size_t pos = find_last_of('.');
362  return pos != npos ? retval.insert(pos, str) : retval.append(str);
363 }
364 
365 // Remove an extension wherever it is ......................................
367 {
368  FileName retval = *this;
369  size_t first = find((String) "." + ext);
370  return (first == npos) ? retval: retval.erase(first, 1 + ext.length());
371 }
372 
373 // Remove the last extension ................................................
375 {
376  FileName retval = *this;
377  size_t first = find_last_of('.');
378  return (first == npos) ? retval : retval.substr(0, first);
379 }
380 
381 // Remove all extensions....................................................
383 {
384  FileName retval = *this;
385  size_t first = find_last_of('/');
386  first = find_first_of('.', first + 1);
387  return (first == npos) ? retval: retval.substr(0, first);
388 }
389 
391 {
392  size_t first = find_last_of('/');
393  return (first == npos) ? "" : substr(0, first);
394 }
395 
397 {
398  size_t first;
399  FileName result;
400  if ((first = rfind(COLON)) != npos)
401  result = substr(first + 1);
402  else if ((first = rfind(".")) != npos)
403  {
404  // Get everything from the '.' to the end of the filename
405  // If there is a '#', only keep whatever is between the '.' and the '#'
406  result = substr(first + 1);
407  result = result.substr(0, result.find(NUM));
408  }
409  else if (find(NUM) != npos)
410  return "raw";
411  return result.toLowercase();
412 }
413 
414 size_t FileName::getFileSize() const
415 {
416  Stat info;
417  if (stat(c_str(), &info))
418  {
419  char cCurrentPath[FILENAME_MAX];
420  char *success=getcwd(cCurrentPath, sizeof(cCurrentPath));
421  if (success==NULL)
422  cCurrentPath[0]='\0';
423  REPORT_ERROR(ERR_UNCLASSIFIED,formatString("FileName::getFileSize: Cannot get size of file %s/%s",cCurrentPath,this->c_str()));
424  }
425  return info.st_size;
426 
427 // int fd = open(c_str(), O_RDONLY);
428 // size_t size = lseek(fd, 0, SEEK_END); // seek to end of file
429 // close(fd);
430 //
431 // return size;
432 
433 }
434 
436 {
437  size_t found = rfind(NUM);
438  if (found != String::npos)
439  return substr(0, found);
440  found = rfind(COLON);
441  if (found != String::npos)
442  return substr(0, found);
443  return *this;
444 }
445 
446 // Get number from file base name ....................................................
448 {
449  size_t skip_directories = find_last_of("/") + 1;
450  size_t point = find_first_of(".", skip_directories);
451  if (point == npos)
452  point = length();
453  size_t root_end = find_last_not_of("0123456789", point - 1);
454  if (root_end + 1 != point)
455  {
456  if (point - root_end > FILENAMENUMBERLENGTH)
457  root_end = point - FILENAMENUMBERLENGTH - 1;
458  String aux = substr(root_end + 1, point - root_end + 1);
459  return atoi(aux.c_str());
460  }
461  else
462  return -1;
463 }
464 
465 // Get number from file ....................................................
466 size_t FileName::getPrefixNumber(size_t pos) const
467 {
468  size_t first = rfind(AT);
469  size_t result = ALL_IMAGES;
470  if (first != npos)
471  {
472  std::vector<String> prefixes;
473  size_t nPref = splitString(substr(0, first),",",prefixes, false);
474 
475  if (pos > nPref-1)
476  REPORT_ERROR(ERR_ARG_INCORRECT, formatString("getPrefixNumber: Selected %lu position greater than %lu positions \n"
477  " detected in %s filename.",pos+1, nPref, this->c_str()));
478 
479  if (isdigit(prefixes[pos].at(0)))
480  result = textToSizeT(prefixes[pos].c_str());
481  }
482  return result;
483 }
484 
486 {
487  size_t first = rfind(AT);
488  String result = "";
489  if (first != npos)
490  {
491  result = substr(0, first);
492  if ((first = result.find(COMMA)) != npos) // Assign and compare at the same time
493  result = result.substr(first+1);
494 
495  /* using isdigit instead of isalpha allows to
496  * detect as blockname rootnames starting by "/"
497  */
498  if (result.empty() || isdigit(result[0]))
499  result = "";
500  }
501  return result;
502 
503 }
504 
506 {
507  size_t first = rfind(AT);
508 
509  if (first != npos)
510  {
511  String block = substr(0, first);
512  size_t second = block.find(COMMA);
513 
514  if (second == npos)
515  {
516  if (!isdigit(block[0])){
517  return substr(first + 1);
518  }
519  }
520  else
521  {
522  String prefix = block.substr(0, second);
523  block = block.substr(second + 1);
524  if (!isdigit(block[0]))
525  return prefix + substr(first);
526  }
527  }
528  return *this;
529 }
530 
532 {
533  size_t first = rfind(AT);
534 
535  if (first != npos)
536  {
537  std::vector<String> prefixes;
538  int nPref = splitString(substr(0, first),",",prefixes, false);
539 
540  if (isdigit(prefixes[nPref-1].at(0)))
541  return substr(first + 1);
542  else if (nPref > 1) // isalpha and we remove the ","
543  return substr(first - prefixes[nPref-1].size());
544  }
545  return *this;
546 }
547 
549 {
550  size_t first = rfind(AT);
551  if (first != npos)
552  return substr(first + 1);
553  return *this;
554 }
555 
556 bool FileName::isMetaData(bool failIfNotExists) const
557 {
558  //check empty string
559  if (empty())
560  REPORT_ERROR(ERR_ARG_INCORRECT, "FileName::isMetaData: Empty string is not a MetaData");
561  //file names containing : or % are not metadatas
562  //size_t found = this->find('@');
563  if (find_first_of(":#") != npos)
564  return false;
565 
566  //check if file exists
567  if (failIfNotExists && !existsTrim())
568  REPORT_ERROR(ERR_IO_NOTFILE, formatString("FileName::isMetaData: File: '%s' does not exist", c_str()));
569  //This is dangerous and should be removed
570  //in next version. only star1 files should be OK
571  //ROB
572  //FIXME
573  return (hasMetadataExtension() || isStar1(failIfNotExists));
574 }
575 
576 bool FileName::isStar1(bool failIfNotExists) const
577 {
578  std::ifstream infile( this->removeAllPrefixes().c_str(), std::ios_base::in);
579  String line;
580 
581  if (infile.fail())
582  {
583  if (failIfNotExists)
584  REPORT_ERROR( ERR_IO_NOTEXIST, formatString("File '%s' does not exist.", this->removeAllPrefixes().c_str()));
585  else
586  return false;
587  }
588 
589  // Search for xmipp_3,
590  char cline[128];
591  infile.getline(cline, 128);
592  infile.close();
593  line = cline;
594  size_t pos = line.find(METADATA_XMIPP_STAR);
595  return (pos != npos); // xmipp_star_1 token found
596 }
597 
598 // Replace one substring by other .......................................
599 FileName FileName::replaceSubstring(const String &subOld, const String &subNew) const
600 {
601  size_t pos = find(subOld);
602  if (pos == npos)
603  return *this;
604 
605  FileName result = *this;
606  result.replace(pos, subOld.length(), subNew);
607  return result;
608 }
609 
610 // Replace all appearances of one substring by other .......................................
611 FileName FileName::replaceCharacter(char oldChar, char newChar) const
612 {
613  FileName result = *this;
614  std::replace(result.begin(), result.end(), oldChar, newChar);
615  return result;
616 }
617 
618 // Substitute one extension by other .......................................
620 {
621  return removeLastExtension() + "." + newExt;
622 }
623 
624 // Remove a substring ......................................................
626 {
627  return replaceSubstring(sub, "");
628 }
629 
630 // Remove until prefix .....................................................
632 {
633  size_t pos = find(prefix);
634  if (pos == npos)
635  return *this;
636  FileName result = *this;
637  return result.erase(0, pos + prefix.length());
638 }
639 
640 // Remove directories ......................................................
642 {
643  size_t last_slash = rfind("/");
644  int tokeep = keep;
645  while (tokeep > 0)
646  {
647  last_slash = rfind("/", last_slash - 1);
648  tokeep--;
649  }
650  if (last_slash == npos)
651  return *this;
652  else
653  return substr(last_slash + 1, length() - last_slash);
654 }
655 
656 void FileName::copyFile(const FileName & target) const
657 {
658  std::ifstream f1(this->c_str(), std::fstream::binary);
659  std::ofstream
660  f2(target.c_str(), std::fstream::trunc | std::fstream::binary);
661  f2 << f1.rdbuf();
662 }
663 
664 /* Check if a file exists -------------------------------------------------- */
665 bool FileName::exists() const
666 {
668 }
669 /* Delete file exists -------------------------------------------------- */
671 {
673  if (temp.exists())
674  unlink(temp.c_str());
675 }
676 /* Check if a file exists remove leading @ and tailing : */
678 {
679  FileName auxF(*this);
680  size_t found = find_first_of(AT);
681 
682  if (found != String::npos)
683  auxF = substr(found+1);
684 
685  found = auxF.find_first_of(NUM);
686 
687  if ( found != String::npos)
688  auxF = auxF.substr(0, found);
689  found = auxF.find_first_of(COLON);
690 
691  if (found != String::npos)
692  auxF = auxF.substr(0, found);
693  return fileExists(auxF.c_str());
694 }
695 
696 /* List of files within a directory ---------------------------------------- */
697 void FileName::getFiles(std::vector<FileName> &files) const
698 {
699  files.clear();
700 
701  DIR *dp;
702  struct dirent *dirp;
703  if ((dp = opendir(c_str())) == NULL)
705 
706  while ((dirp = readdir(dp)) != NULL)
707  if (strcmp(dirp->d_name,".")!=0 && strcmp(dirp->d_name,"..")!=0)
708  files.push_back(FileName(dirp->d_name));
709  closedir(dp);
710  std::sort(files.begin(),files.end());
711 }
712 
713 /* Is directory ------------------------------------------------------------ */
714 bool FileName::isDir() const
715 {
716  Stat st_buf;
717  if (stat (c_str(), &st_buf) != 0)
718  REPORT_ERROR(ERR_UNCLASSIFIED,(String)"Cannot determine status of filename "+ *this);
719  return (S_ISDIR (st_buf.st_mode));
720 }
721 
722 /* Wait until file has a stable size --------------------------------------- */
723 void FileName::waitUntilStableSize(size_t time_step)
724 {
725  size_t idx;
726  FileName basicName;
727  decompose(idx, basicName);
728 
729  if (!exists())
730  return;
731  Stat info1, info2;
732  if (stat(basicName.c_str(), &info1))
734  (String)"FileName::waitUntilStableSize: Cannot get size of file " + *this);
735  off_t size1 = info1.st_size;
736  do
737  {
738  usleep(time_step);
739  if (stat(basicName.c_str(), &info2))
741  (String)"FileName::waitUntilStableSize: Cannot get size of file " + *this);
742  off_t size2 = info2.st_size;
743  if (size1 == size2)
744  break;
745  size1 = size2;
746  }
747  while (true);
748  return;
749 }
750 
751 /* Create empty file ------------------------------------------------------- */
752 void FileName::createEmptyFile(size_t size, size_t block_size)
753 {
754  unsigned char * buffer = (unsigned char*) calloc(sizeof(unsigned char),
755  block_size);
756  if (buffer == NULL)
757  REPORT_ERROR(ERR_MEM_NOTENOUGH, "create_empty_file: No memory left");
758  FILE * fd = fopen(c_str(), "w");
759  if (fd == NULL)
760  REPORT_ERROR(ERR_IO_NOTOPEN, (String)"FileName::createEmptyFile: Cannot open file" + *this);
761  for (size_t i = 0; i < size / block_size; i++)
762  fwrite(buffer, sizeof(unsigned char), block_size, fd);
763  fwrite(buffer, sizeof(unsigned char), size % block_size, fd);
764  fclose(fd);
765  free(buffer);
766 }
767 
769 {
770  FILE* fMap = fopen(c_str(),"wb");
771  if (!fMap)
773  if (length>0)
774  {
775  char c=0;
776  if ((fseek(fMap, length-1, SEEK_SET) == -1) || (fwrite(&c,1,1,fMap) != 1))
777  REPORT_ERROR(ERR_IO_NOWRITE,"FileName::createEmptyFileWithGivenLength: Cannot create empty file");
778  }
779  fclose(fMap);
780 }
781 
785 int do_mkdir(const char *path, mode_t mode)
786 {
787  Stat st;
788  int status = 0;
789 
790  if (stat(path, &st) != 0)
791  {
792  /* Directory does not exist */
793 #ifndef __MINGW32__
794  if (mkdir(path, mode) != 0)
795 #else
796 
797  if (mkdir(path) != 0)
798 #endif
799 
800  status = -1;
801  }
802  else if (!S_ISDIR(st.st_mode))
803  {
804  errno = ENOTDIR;
805  status = -1;
806  }
807 
808  return (status);
809 }
810 
811 int FileName::makePath(mode_t mode) const
812 {
813  char *pp;
814  char *sp;
815  int status;
816  char *copypath = strdup(c_str());
817  if (copypath == NULL)
818  REPORT_ERROR(ERR_MEM_BADREQUEST,"FileName::makePath: Canot alloc memory");
819 
820  status = 0;
821  pp = copypath;
822  while (status == 0 && (sp = strchr(pp, '/')) != 0)
823  {
824  if (sp != pp)
825  {
826  /* Neither root nor double slash in path */
827  *sp = '\0';
828  status = do_mkdir(copypath, mode);
829  *sp = '/';
830  }
831  pp = sp + 1;
832  }
833  if (status == 0)
834  status = do_mkdir(c_str(), mode);
835  free(copypath);
836  return status;
837 }
838 
839 /* Exit program if filename is not empry and file does not exist ----------- */
841 {
842  if (!empty() && !exists())
843  {
844  std::cerr << "FileName::assertExists: control file" << *this
845  << " doesn't exist, exiting..." << std::endl;
846  exit(ERR_IO_NOTEXIST);
847  }
848  //TODO: Maybe change to report error???
849  //REPORT_ERROR(ERR_IO_NOTEXIST, (String)"FileName::assertExists: control file" + *this " doesn't exist, exiting...");
850 }
851 
852 /* Get the Xmipp Base directory -------------------------------------------- */
853 char * getXmippPath()
854 {
855  char* path = getenv("XMIPP_HOME");
856  if (path == NULL)
857  REPORT_ERROR(ERR_VALUE_EMPTY, "getXmippPath::Variable XMIPP_HOME is not defined");
858  return path;
859 
860 }
861 
862 /* Get the Xmipp source directory -------------------------------------------- */
864 {
865  char* path = getenv("XMIPP_SRC");
866  if (path == NULL)
867  REPORT_ERROR(ERR_VALUE_EMPTY, "getXmippSrcPath::Variable XMIPP_HOME is not defined");
868  return path;
869 
870 }
871 
872 void copyImage(const FileName & source, const FileName & target)
873 {
874  ImageGeneric img(source);
875  img.write(target);
876 }
877 
878 void deleteFile(const FileName &fn)
879 {
880  fn.deleteFile();
881 }
882 
883 void FileLock::lock(int _fileno)
884 {
885 #ifndef __MINGW32__
886  if (islocked)
887  unlock();
888 
889  if (_fileno != 0)
890  filenum = _fileno;
891 
892  fl.l_type = F_WRLCK;
893  fcntl(filenum, F_SETLKW, &fl);
894  islocked = true;
895 #endif
896 
897 }
898 
899 void FileLock::lock(FILE * hdlFile)
900 {
901  if (islocked)
902  unlock();
903 
904  if (hdlFile != NULL)
905  this->filenum = fileno(hdlFile);
906 
907 #ifdef __MINGW32__
908 
909  HANDLE hFile = (HANDLE)_get_osfhandle(filenum);
910  DWORD dwLastPos = SetFilePointer(hFile, 0, NULL, FILE_END);
911  if (LockFile(hFile, 0, 0, dwLastPos, 0) != NULL)
912  REPORT_ERROR(ERR_IO_LOCKED,"File cannot be locked.");
913 #else
914 
915  fl.l_type = F_WRLCK;
916  fcntl(filenum, F_SETLKW, &fl);
917 #endif
918 
919  islocked = true;
920 }
921 
922 
924 {
925  if (islocked)
926  {
927 #ifdef __MINGW32__
928  HANDLE hFile = (HANDLE)_get_osfhandle(filenum);
929  DWORD dwLastPos = SetFilePointer(hFile, 0, NULL, FILE_END);
930  if (UnlockFile(hFile, 0, 0, dwLastPos, 0) != NULL)
931  REPORT_ERROR(ERR_IO_LOCKED,"File cannot be unlocked.");
932 #else
933 
934  fl.l_type = F_UNLCK;
935  fcntl(filenum, F_SETLK, &fl);
936 #endif
937 
938  islocked = false;
939  }
940 }
941 
Index out of bounds.
Definition: xmipp_error.h:132
Just to locate unclassified errors.
Definition: xmipp_error.h:192
Empty value.
Definition: xmipp_error.h:194
void write(const FileName &name="", size_t select_img=ALL_IMAGES, bool isStack=false, int mode=WRITE_OVERWRITE, CastWriteMode castMode=CW_CAST, int _swapWrite=0)
#define NUM
int do_mkdir(const char *path, mode_t mode)
FileName removeLastExtension() const
void waitUntilStableSize(size_t time_step=250000)
String getBlockName() const
Just an error for debugging purpose.
Definition: xmipp_error.h:119
#define REPORT_ERROR(nerr, ErrormMsg)
Definition: xmipp_error.h:211
FileName removeFileFormat() const
FileName replaceExtension(const String &newExt) const
doublereal * c
char * getXmippPath()
void copyImage(const FileName &source, const FileName &target)
#define pp(s, x)
Definition: ml2d.cpp:473
std::vector< SelLine >::iterator find(std::vector< SelLine > &text, const std::string &img_name)
Definition: selfile.cpp:553
void setMetadataVersion(String version)
HBITMAP buffer
Definition: svm-toy.cpp:37
Couldn&#39;t write to file.
Definition: xmipp_error.h:140
FileName removePrefixNumber() const
FileName addExtension(const String &ext) const
FileName insertBeforeExtension(const String &str) const
There is not enough memory for allocation.
Definition: xmipp_error.h:166
void createEmptyFileWithGivenLength(size_t length=0) const
void compose(const String &str, const size_t no, const String &ext="")
String getMetadataVersion(void)
FileName removeDirectories(int keep=0) const
FileName beforeLastOf(const String &str) const
void unlock()
Unlock.
void initUniqueName(const char *templateStr="xmippTemp_XXXXXX", const String &fnDir="")
bool hasImageExtension() const
FileName removeAllExtensions() const
void decompose(size_t &no, String &str) const
bool existsTrim() const
String FileNameVersion
bool isDir() const
Bad amount of memory requested.
Definition: xmipp_error.h:165
#define i
void getFiles(std::vector< FileName > &files) const
FileName afterLastOf(const String &str) const
String getExtension() const
double rnd_unif()
FileName removeAllPrefixes() const
FileName afterFirstOf(const String &str) const
glob_log first
FileName replaceSubstring(const String &subOld, const String &subNew) const
FileName addPrefix(const String &prefix) const
It is not a file.
Definition: xmipp_error.h:141
#define FLOOR(x)
Definition: xmipp_macros.h:240
FileName removeFilename() const
FileName beforeFirstOf(const String &str) const
int in
int splitString(const String &input, const String &delimiter, StringVector &results, bool includeEmpties)
size_t getPrefixNumber(size_t pos=0) const
Incorrect argument received.
Definition: xmipp_error.h:113
#define COMMA
#define FILENAME_MAX
Definition: defines.h:43
#define AT
void composeBlock(const String &blockName, size_t no, const String &str, const String &ext="")
FileName getRoot() const
bool isStar1(bool failIfNotExists) const
free((char *) ob)
int makePath(mode_t mode=0755) const
__host__ __device__ float length(float2 v)
File or directory does not exist.
Definition: xmipp_error.h:136
FileName replaceCharacter(char oldChar, char newChar) const
void mode
bool contains(const String &str) const
FileName withoutRoot() const
bool exists() const
FileName removeUntilPrefix(const String &prefix) const
void sort(struct DCEL_T *dcel)
Definition: sorting.cpp:18
FileName toLowercase() const
void assertExists()
void deleteFile() const
int trunc(double x)
Definition: ap.cpp:7248
File cannot be open.
Definition: xmipp_error.h:137
#define len
void createEmptyFile(size_t size, size_t block_size=102400)
void lock(int fileno=0)
Lock file.
bool isMetaData(bool failIfNotExists=true) const
FileName removeBlockName() const
FileName withoutExtension() const
std::string String
Definition: xmipp_strings.h:34
#define ALL_IMAGES
bool fileExists(const char *filename)
String formatString(const char *format,...)
Error when locking/unloking a file.
Definition: xmipp_error.h:144
String getFileFormat() const
#define FILENAMENUMBERLENGTH
int getNumber() const
FileName getDir() const
#define FIRST_IMAGE
FileName removeSubstring(const String &sub) const
bool hasVolumeExtension() const
FileName toUppercase() const
#define METADATA_XMIPP_STAR
char * getXmippSrcPath()
struct stat Stat
void copyFile(const FileName &target) const
unsigned int randomize_random_generator()
bool hasStackExtension() const
#define COLON
FileName getBaseName() const
bool hasMetadataExtension() const
size_t textToSizeT(const char *str)
FileName removeExtension(const String &ext) const
size_t getFileSize() const
void formatStringFast(String &str, const char *format,...)
bool isInStack() const
FileName getDecomposedFileName() const
void initRandom(int length)