svn update: 60286 (latest:60286)
[profile/ivi/ecore.git] / src / lib / ecore_file / ecore_file.c
1 #ifdef HAVE_CONFIG_H
2 # include <config.h>
3 #endif
4
5 #include <stdio.h>
6 #include <string.h>
7
8 #ifndef _MSC_VER
9 # include <unistd.h>
10 # include <libgen.h>
11 #endif
12
13 #ifdef HAVE_FEATURES_H
14 # include <features.h>
15 #endif
16 #include <ctype.h>
17 #include <errno.h>
18
19 #include "ecore_file_private.h"
20
21 int _ecore_file_log_dom = -1;
22 static int _ecore_file_init_count = 0;
23
24 /* externally accessible functions */
25
26 /**
27  * @addtogroup Ecore_File_Group Ecore_File - Files and directories convenience functions
28  *
29  * @{
30  */
31
32 /**
33  * @brief Initialize the Ecore_File library.
34  *
35  * @return 1 or greater on success, 0 on error.
36  *
37  * This function sets up Ecore_File and the services it will use
38  * (monitoring, downloading, PATH related feature). It returns 0 on
39  * failure, otherwise it returns the number of times it has already
40  * been called.
41  *
42  * When Ecore_File is not used anymore, call ecore_file_shutdown()
43  * to shut down the Ecore_File library.
44  */
45 EAPI int
46 ecore_file_init()
47 {
48    if (++_ecore_file_init_count != 1)
49      return _ecore_file_init_count;
50
51    if (!ecore_init())
52      return --_ecore_file_init_count;
53
54    _ecore_file_log_dom = eina_log_domain_register
55      ("ecore_file", ECORE_FILE_DEFAULT_LOG_COLOR);
56    if(_ecore_file_log_dom < 0)
57      {
58        EINA_LOG_ERR("Impossible to create a log domain for the ecore file module.");
59        return --_ecore_file_init_count;
60      }
61    ecore_file_path_init();
62    ecore_file_monitor_init();
63    ecore_file_download_init();
64
65    /* FIXME: were the tests disabled for a good reason ? */
66
67    /*
68    if (!ecore_file_monitor_init())
69      goto shutdown_ecore_file_path;
70
71    if (!ecore_file_download_init())
72      goto shutdown_ecore_file_monitor;
73    */
74
75    return _ecore_file_init_count;
76
77    /*
78  shutdown_ecore_file_monitor:
79    ecore_file_monitor_shutdown();
80  shutdown_ecore_file_path:
81    ecore_file_path_shutdown();
82
83    return --_ecore_file_init_count;
84    */
85 }
86
87 /**
88  * @brief Shut down the Ecore_File library.
89  *
90  * @return 0 when the library is completely shut down, 1 or
91  * greater otherwise.
92  *
93  * This function shuts down the Ecore_File library. It returns 0 when it has
94  * been called the same number of times than ecore_file_init(). In that case
95  * it shuts down all the services it uses.
96  */
97 EAPI int
98 ecore_file_shutdown()
99 {
100    if (--_ecore_file_init_count != 0)
101      return _ecore_file_init_count;
102
103    ecore_file_download_shutdown();
104    ecore_file_monitor_shutdown();
105    ecore_file_path_shutdown();
106
107    eina_log_domain_unregister(_ecore_file_log_dom);
108    _ecore_file_log_dom = -1;
109
110    ecore_shutdown();
111
112    return _ecore_file_init_count;
113 }
114
115 /**
116  * @brief Get the time of the last modification to the given file.
117  *
118  * @param file The name of the file.
119  * @return Return the time of the last data modification, or 0 on
120  * failure.
121  *
122  * This function returns the time of the last modification of
123  * @p file. On failure, it returns 0.
124  */
125 EAPI long long
126 ecore_file_mod_time(const char *file)
127 {
128    struct stat st;
129
130    if (stat(file, &st) < 0) return 0;
131    return st.st_mtime;
132 }
133
134 /**
135  * @brief Get the size of the given file.
136  *
137  * @param file The name of the file.
138  * @return Return the size of the file in bytes, or 0 on failure.
139  *
140  * This function returns the size of @p file in bytes. On failure, it
141  * returns 0.
142  */
143 EAPI long long
144 ecore_file_size(const char *file)
145 {
146    struct stat st;
147
148    if (stat(file, &st) < 0) return 0;
149    return st.st_size;
150 }
151
152 /**
153  * @brief Check if the given file exists.
154  *
155  * @param file The name of the file.
156  * @return Return EINA_TRUE if the file exists, EINA_FALSE otherwise.
157  *
158  * This function returns EINA_TRUE if @p file exists on local filesystem,
159  * EINA_FALSE otherwise.
160  */
161 EAPI Eina_Bool
162 ecore_file_exists(const char *file)
163 {
164    struct stat st;
165    if (!file) return EINA_FALSE;
166
167    /*Workaround so that "/" returns a true, otherwise we can't monitor "/" in ecore_file_monitor*/
168    if (stat(file, &st) < 0 && strcmp(file, "/")) return EINA_FALSE;
169    return EINA_TRUE;
170 }
171
172 /**
173  * @brief Check if the given file is a directory.
174  *
175  * @param file The name of the file.
176  * @return Return EINA_TRUE if the file exists and is a directory,
177  * EINA_FALSE otherwise.
178  *
179  * This function returns EINA_TRUE if @p file exists exists and is a
180  * directory on local filesystem, EINA_FALSE otherwise.
181  */
182 EAPI Eina_Bool
183 ecore_file_is_dir(const char *file)
184 {
185    struct stat st;
186
187    if (stat(file, &st) < 0) return EINA_FALSE;
188    if (S_ISDIR(st.st_mode)) return EINA_TRUE;
189    return EINA_FALSE;
190 }
191
192 static mode_t default_mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
193
194 /**
195  * @brief Create a new directory.
196  *
197  * @param  dir The name of the directory to create
198  * @return EINA_TRUE on successful creation, EINA_FALSE otherwise.
199  *
200  * This function creates the directory @p dir with the mode S_IRUSR |
201  * S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH. On
202  * success, it returns EINA_TRUE, EINA_FALSE otherwise.
203  */
204 EAPI Eina_Bool
205 ecore_file_mkdir(const char *dir)
206 {
207    if (mkdir(dir, default_mode) < 0) return EINA_FALSE;
208    return EINA_TRUE;
209 }
210
211 /**
212  * @brief Create complete directory in a batch.
213  *
214  * @param dirs The list of directories, null terminated.
215  * @return The number of successful directories created, -1 if dirs is
216  * @c NULL.
217  *
218  * This function creates all the directories that are in the null
219  * terminated array @p dirs. The function loops over the directories
220  * and call ecore_file_mkdir(). This function returns -1 if @p dirs is
221  * @c NULL, otherwise if returns the number of suceesfully created
222  * directories.
223  */
224 EAPI int
225 ecore_file_mkdirs(const char **dirs)
226 {
227    int i = 0;
228
229    if (!dirs) return -1;
230
231    for (; *dirs; dirs++)
232      if (ecore_file_mkdir(*dirs))
233        i++;
234    return i;
235 }
236
237 /**
238  * @brief Create complete list of sub-directories in a batch (optimized).
239  *
240  * @param base The base directory to act on.
241  * @param subdirs The list of directories, null terminated.
242  * @return number of successful directories created, -1 on failure.
243  *
244  * This function creates all the directories that are in the null
245  * terminated array @p dirs in the @p base directory. If @p base does
246  * not exist, it will be created. The function loops over the directories
247  * and call ecore_file_mkdir(). The whole path of the directories must
248  * exist. So if base/a/b/c wants to be created, @p subdirs must
249  * contain "a", "a/b" and "a/b/c", in that order. This function
250  * returns -1 if @p dirs or @p base are @c NULL, or if @p base is
251  * empty ("\0"). It returns 0 is @p base is not a directory or
252  * invalid, or if it can't be created. Otherwise if returns the number
253  * of suceesfully created directories.
254  */
255 EAPI int
256 ecore_file_mksubdirs(const char *base, const char **subdirs)
257 {
258 #ifndef HAVE_ATFILE_SOURCE
259    char buf[PATH_MAX];
260    int baselen;
261 #else
262    int fd;
263    DIR *dir;
264 #endif
265    int i;
266
267    if (!subdirs) return -1;
268    if ((!base) || (base[0] == '\0')) return -1;
269
270    if ((!ecore_file_is_dir(base)) && (!ecore_file_mkpath(base)))
271      return 0;
272
273 #ifndef HAVE_ATFILE_SOURCE
274    baselen = eina_strlcpy(buf, base, sizeof(buf));
275    if ((baselen < 1) || (baselen + 1 >= (int)sizeof(buf)))
276      return 0;
277
278    if (buf[baselen - 1] != '/')
279      {
280         buf[baselen] = '/';
281         baselen++;
282      }
283 #else
284    dir = opendir(base);
285    if (!dir)
286      return 0;
287    fd = dirfd(dir);
288 #endif
289
290    i = 0;
291    for (; *subdirs; subdirs++)
292      {
293         struct stat st;
294
295 #ifndef HAVE_ATFILE_SOURCE
296         eina_strlcpy(buf + baselen, *subdirs, sizeof(buf) - baselen);
297         if (stat(buf, &st) == 0)
298 #else
299         if (fstatat(fd, *subdirs, &st, 0) == 0)
300 #endif
301           {
302              if (S_ISDIR(st.st_mode))
303                {
304                   i++;
305                   continue;
306                }
307           }
308         else
309           {
310              if (errno == ENOENT)
311                {
312 #ifndef HAVE_ATFILE_SOURCE
313                   if (mkdir(buf, default_mode) == 0)
314 #else
315                   if (mkdirat(fd, *subdirs, default_mode) == 0)
316 #endif
317                     {
318                        i++;
319                        continue;
320                     }
321                  }
322             }
323      }
324
325 #ifdef HAVE_ATFILE_SOURCE
326    closedir(dir);
327 #endif
328
329    return i;
330 }
331
332 /**
333  * @brief Delete the given directory.
334  *
335  * @param  dir The name of the directory to delete.
336  * @return EINA_TRUE on success, EINA_FALSE otherwise.
337  *
338  * This function deletes @p dir. It returns EINA_TRUE on success,
339  * EINA_FALSE otherwise.
340  */
341 EAPI Eina_Bool
342 ecore_file_rmdir(const char *dir)
343 {
344    if (rmdir(dir) < 0) return EINA_FALSE;
345    return EINA_TRUE;
346 }
347
348 /**
349  * @brief Delete the given file.
350  *
351  * @param  file The name of the file to delete.
352  * @return EINA_TRUE on success, EINA_FALSE otherwise.
353  *
354  * This function deletes @p file. It returns EINA_TRUE on success,
355  * EINA_FALSE otherwise.
356  */
357 EAPI Eina_Bool
358 ecore_file_unlink(const char *file)
359 {
360    if (unlink(file) < 0) return EINA_FALSE;
361    return EINA_TRUE;
362 }
363
364 /**
365  * @brief Remove the given file or directory.
366  *
367  * @param  file The name of the file or directory to delete.
368  * @return EINA_TRUE on success, EINA_FALSE otherwise.
369  *
370  * This function removes @p file. It returns EINA_TRUE on success,
371  * EINA_FALSE otherwise.
372  */
373 EAPI Eina_Bool
374 ecore_file_remove(const char *file)
375 {
376    if (remove(file) < 0) return EINA_FALSE;
377    return EINA_TRUE;
378 }
379
380 /**
381  * @brief Delete the given directory and all its contents.
382  *
383  * @param  dir The name of the directory to delete.
384  * @return EINA_TRUE on success, EINA_FALSE otherwise.
385  *
386  * This function delete @p dir and all its contents. If @p dir is a
387  * link only the link is removed. It returns EINA_TRUE on success,
388  * EINA_FALSE otherwise.
389  */
390 EAPI Eina_Bool
391 ecore_file_recursive_rm(const char *dir)
392 {
393    DIR *dirp;
394    struct dirent *dp;
395    char path[PATH_MAX], buf[PATH_MAX];
396    struct stat st;
397    int ret;
398
399    if (readlink(dir, buf, sizeof(buf)) > 0)
400      return ecore_file_unlink(dir);
401
402    ret = stat(dir, &st);
403    if ((ret == 0) && (S_ISDIR(st.st_mode)))
404      {
405         ret = 1;
406         if (stat(dir, &st) == -1) return EINA_FALSE;
407         dirp = opendir(dir);
408         if (dirp)
409           {
410              while ((dp = readdir(dirp)))
411                {
412                   if ((strcmp(dp->d_name, ".")) && (strcmp(dp->d_name, "..")))
413                     {
414                        snprintf(path, PATH_MAX, "%s/%s", dir, dp->d_name);
415                        if (!ecore_file_recursive_rm(path))
416                          ret = 0;
417                     }
418                }
419              closedir(dirp);
420           }
421         if (!ecore_file_rmdir(dir)) ret = 0;
422         if (ret)
423             return EINA_TRUE;
424         else
425             return EINA_FALSE;
426      }
427    else
428      {
429         if (ret == -1) return EINA_FALSE;
430         return ecore_file_unlink(dir);
431      }
432 }
433
434 static inline Eina_Bool
435 _ecore_file_mkpath_if_not_exists(const char *path)
436 {
437    struct stat st;
438
439    /* Windows: path like C: or D: etc are valid, but stat() returns an error */
440 #ifdef _WIN32
441    if ((strlen(path) == 2) &&
442        ((path[0] >= 'a' && path[0] <= 'z') ||
443         (path[0] >= 'A' && path[0] <= 'Z')) &&
444        (path[1] == ':'))
445      return EINA_TRUE;
446 #endif
447
448    if (stat(path, &st) < 0)
449      return ecore_file_mkdir(path);
450    else if (!S_ISDIR(st.st_mode))
451      return EINA_FALSE;
452    else
453      return EINA_TRUE;
454 }
455
456 /**
457  * @brief Create a complete path.
458  *
459  * @param  path The path to create
460  * @return EINA_TRUE on success, EINA_FALSE otherwise.
461  *
462  * This function creates @p path and all the subdirectories it
463  * contains. The separator is '/' or '\'. If @p path exists, this
464  * function returns EINA_TRUE immediately. It returns EINA_TRUE on
465  * success, EINA_FALSE otherwise.
466  */
467 EAPI Eina_Bool
468 ecore_file_mkpath(const char *path)
469 {
470    char ss[PATH_MAX];
471    unsigned int i;
472
473    if (ecore_file_is_dir(path))
474      return EINA_TRUE;
475
476    for (i = 0; path[i] != '\0'; ss[i] = path[i], i++)
477      {
478         if (i == sizeof(ss) - 1) return EINA_FALSE;
479         if (((path[i] == '/') || (path[i] == '\\')) && (i > 0))
480           {
481              ss[i] = '\0';
482              if (!_ecore_file_mkpath_if_not_exists(ss))
483                return EINA_FALSE;
484           }
485      }
486    ss[i] = '\0';
487    return _ecore_file_mkpath_if_not_exists(ss);
488 }
489
490 /**
491  * @brief Create complete paths in a batch.
492  *
493  * @param paths list of paths, null terminated.
494  * @return number of successful paths created, -1 if paths is NULL.
495  *
496  * This function creates all the directories that are in the null
497  * terminated array @p paths. The function loops over the directories
498  * and call ecore_file_mkpath(), hence on Windows, '\' must be
499  * replaced by '/' before calling that function. This function
500  * returns -1 if @p paths is @c NULL. Otherwise if returns the number
501  * of suceesfully created directories.
502  */
503 EAPI int
504 ecore_file_mkpaths(const char **paths)
505 {
506    int i = 0;
507
508    if (!paths) return -1;
509
510    for (; *paths; paths++)
511      if (ecore_file_mkpath(*paths))
512        i++;
513    return i;
514 }
515
516 /**
517  * @brief Copy the given file to the given destination.
518  *
519  * @param  src The name of the source file.
520  * @param  dst The name of the destination file.
521  * @return EINA_TRUE on success, EINA_FALSE otherwise.
522  *
523  * This function copies @p src to @p dst. If the absolute path name of
524  * @p src and @p dst can not be computed, or if they are equal, or if
525  * the copy fails, the function returns EINA_FALSE, otherwise it
526  * returns EINA_TRUE.
527  */
528 EAPI Eina_Bool
529 ecore_file_cp(const char *src, const char *dst)
530 {
531    FILE *f1, *f2;
532    char buf[16384];
533    char realpath1[PATH_MAX], realpath2[PATH_MAX];
534    size_t num;
535    Eina_Bool ret = EINA_TRUE;
536
537    if (!realpath(src, realpath1)) return EINA_FALSE;
538    if (realpath(dst, realpath2) && !strcmp(realpath1, realpath2)) return EINA_FALSE;
539
540    f1 = fopen(src, "rb");
541    if (!f1) return EINA_FALSE;
542    f2 = fopen(dst, "wb");
543    if (!f2)
544      {
545         fclose(f1);
546         return EINA_FALSE;
547      }
548    while ((num = fread(buf, 1, sizeof(buf), f1)) > 0)
549      {
550         if (fwrite(buf, 1, num, f2) != num) ret = EINA_FALSE;
551      }
552    fclose(f1);
553    fclose(f2);
554    return ret;
555 }
556
557 /**
558  * @brief Move the given file to the given destination.
559  *
560  * @param  src The name of the source file.
561  * @param  dst The name of the destination file.
562  * @return EINA_TRUE on success, EINA_FALSE otherwise.
563  *
564  * This function moves @p src to @p dst. It returns EINA_TRUE on
565  * success, EINA_FALSE otherwise.
566  */
567 EAPI Eina_Bool
568 ecore_file_mv(const char *src, const char *dst)
569 {
570    char buf[PATH_MAX];
571    int fd;
572
573    if (rename(src, dst))
574      {
575         // File cannot be moved directly because
576         // it resides on a different mount point.
577         if (errno == EXDEV)
578           {
579              struct stat st;
580
581              // Make sure this is a regular file before
582              // we do anything fancy.
583              stat(src, &st);
584              if (S_ISREG(st.st_mode))
585                {
586                   char *dir;
587
588                   dir = ecore_file_dir_get(dst);
589                   // Since we can't directly rename, try to
590                   // copy to temp file in the dst directory
591                   // and then rename.
592                   snprintf(buf, sizeof(buf), "%s/.%s.tmp.XXXXXX",
593                            dir, ecore_file_file_get(dst));
594                   free(dir);
595                   fd = mkstemp(buf);
596                   if (fd < 0)
597                     {
598                        perror("mkstemp");
599                        goto FAIL;
600                     }
601                   close(fd);
602
603                   // Copy to temp file
604                   if (!ecore_file_cp(src, buf))
605                     goto FAIL;
606
607                   // Set file permissions of temp file to match src
608                   chmod(buf, st.st_mode);
609
610                   // Try to atomically move temp file to dst
611                   if (rename(buf, dst))
612                     {
613                        // If we still cannot atomically move
614                        // do a normal copy and hope for the best.
615                        if (!ecore_file_cp(buf, dst))
616                          goto FAIL;
617                     }
618
619                   // Delete temporary file and src
620                   ecore_file_unlink(buf);
621                   ecore_file_unlink(src);
622                   goto PASS;
623                }
624           }
625         goto FAIL;
626      }
627
628 PASS:
629    return EINA_TRUE;
630
631 FAIL:
632    return EINA_FALSE;
633 }
634
635 /**
636  * @brief Create a symbolic link.
637  *
638  * @param  src The name of the file to link.
639  * @param  dest The name of link.
640  * @return EINA_TRUE on success, EINA_FALSE otherwise.
641  *
642  * This function create the symbolic link @p dest of @p src. This
643  * function does not work on Windows. It returns EINA_TRUE on success,
644  * EINA_FALSE otherwise.
645  */
646 EAPI Eina_Bool
647 ecore_file_symlink(const char *src, const char *dest)
648 {
649    if (!symlink(src, dest)) return EINA_TRUE;
650
651    return EINA_FALSE;
652 }
653
654 /**
655  * @brief Get the canonicalized absolute path name.
656  *
657  * @param  file The file path.
658  * @return The canonicalized absolute pathname or an empty string on
659  * failure.
660  *
661  * This function returns the absolute path name of @p file as a newly
662  * allocated string. If @p file is @c NULL, or on error, this function
663  * returns an empty string. Otherwise, it returns the absolute path
664  * name. When not needed anymore, the returned value must be freed.
665  */
666 EAPI char *
667 ecore_file_realpath(const char *file)
668 {
669    char buf[PATH_MAX];
670
671    /*
672     * Some implementations of realpath do not conform to the SUS.
673     * And as a result we must prevent a null arg from being passed.
674     */
675    if (!file) return strdup("");
676    if (!realpath(file, buf)) return strdup("");
677
678    return strdup(buf);
679 }
680
681 /**
682  * Get the filename from a given path.
683  *
684  * @param  path The complete path.
685  * @return The file name.
686  *
687  * This function returns the file name of @p path. If @p path is
688  * @c NULL, the functions returns @c NULL.
689  */
690 EAPI const char *
691 ecore_file_file_get(const char *path)
692 {
693    char *result = NULL;
694
695    if (!path) return NULL;
696    if ((result = strrchr(path, '/'))) result++;
697    else result = (char *)path;
698    return result;
699 }
700
701 /**
702  * @brief Get the directory where the given file resides.
703  *
704  * @param  file The name of the file.
705  * @return The directory name.
706  *
707  * This function returns the directory where @p file resides as anewly
708  * allocated string. If @p file is @c NULL or on error, this function
709  * returns @c NULL. When not needed anymore, the returned value must
710  * be freed.
711  */
712 EAPI char *
713 ecore_file_dir_get(const char *file)
714 {
715    char *p;
716    char buf[PATH_MAX];
717
718    if (!file) return NULL;
719    strncpy(buf, file, PATH_MAX);
720    buf[PATH_MAX - 1] = 0;
721    p = dirname(buf);
722    return strdup(p);
723 }
724
725 /**
726  * @brief Check if the given file can be read.
727  *
728  * @param  file The name of the file.
729  * @return EINA_TRUE if the file is readable, EINA_FALSE otherwise.
730  *
731  * This function returns EINA_TRUE if @p file can be read, EINA_FALSE
732  * otherwise.
733  */
734 EAPI Eina_Bool
735 ecore_file_can_read(const char *file)
736 {
737    if (!file) return EINA_FALSE;
738    if (!access(file, R_OK)) return EINA_TRUE;
739    return EINA_FALSE;
740 }
741
742 /**
743  * @brief Check if the given file can be written.
744  *
745  * @param  file The name of the file.
746  * @return EINA_TRUE if the file is writable, EINA_FALSE otherwise.
747  *
748  * This function returns EINA_TRUE if @p file can be written, EINA_FALSE
749  * otherwise.
750  */
751 EAPI Eina_Bool
752 ecore_file_can_write(const char *file)
753 {
754    if (!file) return EINA_FALSE;
755    if (!access(file, W_OK)) return EINA_TRUE;
756    return EINA_FALSE;
757 }
758
759 /**
760  * @bbrief Check if the given file can be executed.
761  *
762  * @param  file The name of the file.
763  * @return EINA_TRUE if the file can be executed, EINA_FALSE otherwise.
764  *
765  * This function returns EINA_TRUE if @p file can be executed, EINA_FALSE
766  * otherwise.
767  */
768 EAPI Eina_Bool
769 ecore_file_can_exec(const char *file)
770 {
771    if (!file) return EINA_FALSE;
772    if (!access(file, X_OK)) return EINA_TRUE;
773    return EINA_FALSE;
774 }
775
776 /**
777  * @brief Get the path pointed by the given link.
778  *
779  * @param  lnk The name of the link.
780  * @return The path pointed by link or NULL.
781  *
782  * This function returns the path pointed by @p link as a newly
783  * allocated string. This function does not work on Windows. On
784  * failure, the function returns @c NULL. When not needed anymore, the
785  * returned value must be freed.
786  */
787 EAPI char *
788 ecore_file_readlink(const char *lnk)
789 {
790    char buf[PATH_MAX];
791    int count;
792
793    if ((count = readlink(lnk, buf, sizeof(buf) - 1)) < 0) return NULL;
794    buf[count] = 0;
795    return strdup(buf);
796 }
797
798 /**
799  * @brief Get the list of the files and directories in the given
800  * directory.
801  *
802  * @param  dir The name of the directory to list
803  * @return Return an Eina_List containing all the files in the directory;
804  *         on failure it returns NULL.
805  *
806  * This function returns a list of allocated strings of all the files
807  * and directories contained in @p dir. The list will be sorted with
808  * strcoll as compare function. That means that you may want to set
809  * the current locale for the category LC_COLLATE with
810  * setlocale(). For more information see the manual pages of strcoll
811  * and setlocale. The list will not contain the directory entries for
812  * '.' and '..'. On failure, @c NULL is returned. When not needed
813  * anymore, the list elements must be freed.
814  */
815 EAPI Eina_List *
816 ecore_file_ls(const char *dir)
817 {
818    char *f;
819    DIR *dirp;
820    struct dirent *dp;
821    Eina_List *list = NULL;
822
823    dirp = opendir(dir);
824    if (!dirp) return NULL;
825
826    while ((dp = readdir(dirp)))
827      {
828         if ((strcmp(dp->d_name, ".")) && (strcmp(dp->d_name, "..")))
829           {
830                f = strdup(dp->d_name);
831                list = eina_list_append(list, f);
832           }
833      }
834    closedir(dirp);
835
836    list = eina_list_sort(list, eina_list_count(list), EINA_COMPARE_CB(strcoll));
837
838    return list;
839 }
840
841 /**
842  * @brief Return the executable from the given command.
843  *
844  * @param app The application command, with parameters.
845  *
846  * This function returns the executable from @p app as a newly
847  * allocated string. Arguments are removed and escae characters are
848  * handled. If @p app is @c NULL, or on failure, the function returns
849  * @c NULL. When not needed anymore, the returned value must be freed.
850  */
851 EAPI char *
852 ecore_file_app_exe_get(const char *app)
853 {
854    char *p, *pp, *exe1 = NULL, *exe2 = NULL;
855    char *exe = NULL;
856    int in_quot_dbl = 0, in_quot_sing = 0, restart = 0;
857
858    if (!app) return NULL;
859
860    p = (char *)app;
861 restart:
862    while ((*p) && (isspace(*p))) p++;
863    exe1 = p;
864    while (*p)
865      {
866         if (in_quot_sing)
867           {
868              if (*p == '\'')
869                in_quot_sing = 0;
870           }
871         else if (in_quot_dbl)
872           {
873              if (*p == '\"')
874                in_quot_dbl = 0;
875           }
876         else
877           {
878              if (*p == '\'')
879                in_quot_sing = 1;
880              else if (*p == '\"')
881                in_quot_dbl = 1;
882              if ((isspace(*p)) && (!((p > app) && (p[-1] != '\\'))))
883                break;
884           }
885         p++;
886      }
887    exe2 = p;
888    if (exe2 == exe1) return NULL;
889    if (*exe1 == '~')
890      {
891         char *homedir;
892         int len;
893
894         /* Skip ~ */
895         exe1++;
896
897         homedir = getenv("HOME");
898         if (!homedir) return NULL;
899         len = strlen(homedir);
900         if (exe) free(exe);
901         exe = malloc(len + exe2 - exe1 + 2);
902         if (!exe) return NULL;
903         pp = exe;
904         if (len)
905           {
906              strcpy(exe, homedir);
907              pp += len;
908              if (*(pp - 1) != '/')
909                {
910                   *pp = '/';
911                   pp++;
912                }
913           }
914      }
915    else
916      {
917         if (exe) free(exe);
918         exe = malloc(exe2 - exe1 + 1);
919         if (!exe) return NULL;
920         pp = exe;
921      }
922    p = exe1;
923    restart = 0;
924    in_quot_dbl = 0;
925    in_quot_sing = 0;
926    while (*p)
927      {
928         if (in_quot_sing)
929           {
930              if (*p == '\'')
931                in_quot_sing = 0;
932              else
933                {
934                   *pp = *p;
935                   pp++;
936                }
937           }
938         else if (in_quot_dbl)
939           {
940              if (*p == '\"')
941                in_quot_dbl = 0;
942              else
943                {
944                   /* technically this is wrong. double quotes also accept
945                    * special chars:
946                    *
947                    * $, `, \
948                    */
949                   *pp = *p;
950                   pp++;
951                }
952           }
953         else
954           {
955              /* technically we should handle special chars:
956               *
957               * $, `, \, etc.
958               */
959              if ((p > exe1) && (p[-1] == '\\'))
960                {
961                   if (*p != '\n')
962                     {
963                        *pp = *p;
964                        pp++;
965                     }
966                }
967              else if ((p > exe1) && (*p == '='))
968                {
969                   restart = 1;
970                   *pp = *p;
971                   pp++;
972                }
973              else if (*p == '\'')
974                in_quot_sing = 1;
975              else if (*p == '\"')
976                in_quot_dbl = 1;
977              else if (isspace(*p))
978                {
979                   if (restart)
980                     goto restart;
981                   else
982                     break;
983                }
984              else
985                {
986                   *pp = *p;
987                   pp++;
988                }
989           }
990         p++;
991      }
992    *pp = 0;
993    return exe;
994 }
995
996 /**
997  * @brief Add the escape sequence ('\\') to the given file name.
998  *
999  * @param  filename The file name.
1000  * @return The file name with special characters escaped.
1001  *
1002  * This function adds the escape sequence ('\\') to the given file
1003  * name and returns the result as a newly allocated string. If the
1004  * length of the returned string is longer than PATH_MAX, or on
1005  * failure, @c NULL is returned. When not needed anymore, the returned
1006  * value must be freed.
1007  */
1008 EAPI char *
1009 ecore_file_escape_name(const char *filename)
1010 {
1011    const char *p;
1012    char *q;
1013    char buf[PATH_MAX];
1014
1015    p = filename;
1016    q = buf;
1017    while (*p)
1018      {
1019         if ((q - buf) > (PATH_MAX - 6)) return NULL;
1020         if (
1021             (*p == ' ') || (*p == '\t') || (*p == '\n') ||
1022             (*p == '\\') || (*p == '\'') || (*p == '\"') ||
1023             (*p == ';') || (*p == '!') || (*p == '#') ||
1024             (*p == '$') || (*p == '%') || (*p == '&') ||
1025             (*p == '*') || (*p == '(') || (*p == ')') ||
1026             (*p == '[') || (*p == ']') || (*p == '{') ||
1027             (*p == '}') || (*p == '|') || (*p == '<') ||
1028             (*p == '>') || (*p == '?')
1029             )
1030           {
1031              *q = '\\';
1032              q++;
1033           }
1034         *q = *p;
1035         q++;
1036         p++;
1037      }
1038    *q = 0;
1039    return strdup(buf);
1040 }
1041
1042 /**
1043  * @bried Remove the extension from the given file name.
1044  *
1045  * @param  path The name of the file.
1046  * @return A newly allocated string with the extension stripped out or
1047  * NULL on errors.
1048  *
1049  * This function removes the extension from @p path and returns the
1050  * result as a newly allocated string. If @p path is @c NULL, or on
1051  * failure, the function returns @c NULL. When not needed anymore, the
1052  * returned value must be freed.
1053  */
1054 EAPI char *
1055 ecore_file_strip_ext(const char *path)
1056 {
1057    char *p, *file = NULL;
1058
1059    if (!path)
1060      return NULL;
1061
1062    p = strrchr(path, '.');
1063    if (!p)
1064      file = strdup(path);
1065    else if (p != path)
1066      {
1067         file = malloc(((p - path) + 1) * sizeof(char));
1068         if (file)
1069           {
1070              memcpy(file, path, (p - path));
1071              file[p - path] = 0;
1072           }
1073      }
1074
1075    return file;
1076 }
1077
1078 /**
1079  * @brief Check if the given directory is empty.
1080  *
1081  * @param  dir The name of the directory to check.
1082  * @return 1 if directory is empty, 0 if it has at least one file or
1083  * -1 in case of errors.
1084  *
1085  * This functions checks if @p dir is empty. The '.' and '..' files
1086  * will be ignored. If @p dir is empty, 1 is returned, if it contains
1087  * at least 1 file, 0 is returned. On failure, -1 is returned.
1088  */
1089 EAPI int
1090 ecore_file_dir_is_empty(const char *dir)
1091 {
1092    DIR *dirp;
1093    struct dirent *dp;
1094
1095    dirp = opendir(dir);
1096    if (!dirp) return -1;
1097
1098    while ((dp = readdir(dirp)))
1099      {
1100         if ((strcmp(dp->d_name, ".")) && (strcmp(dp->d_name, "..")))
1101           {
1102              closedir(dirp);
1103              return 0;
1104           }
1105      }
1106
1107    closedir(dirp);
1108    return 1;
1109 }
1110
1111 /**
1112  * @}
1113  */