0

C 从来都不是我的强大力量,但我决定试一试。以下是我的代码,但是在运行时,它给出了分段错误(核心转储)。

基本上我想要的是检查文件夹是否为空(mtp设备安装在其中),如果它是空的,运行mount命令,如果不是,运行另一个命令。

#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
#include <libnotify/notify.h>
#include <stdio.h>
#include <unistd.h>

void main ()
{
  int n = 0;
  struct dirent *d;
  const char *dir_path="~/Nexus";
  DIR *dir = opendir(dir_path);
      while ((d = readdir(dir)) != NULL) {
        if(++n > 2)
          break;
      }
      closedir(dir);
      if (n <= 2) //Directory Empty
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * Mount = notify_notification_new ("Galaxy Nexus", "Mounted at ~/Nexus", "/home/tristan202/bin/test/android_on.png");
    system("jmtpfs ~/Nexus");
    notify_notification_show (Mount, NULL);
    }
      else
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * uMount = notify_notification_new ("Galaxy Nexus", "Unmounted", "/home/tristan202/bin/test/android_off.png");
    system("fusermount -u ~/Nexus");
    notify_notification_show (uMount, NULL);
    }
    }

欢迎任何建议。

编辑

#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
#include <libnotify/notify.h>
#include <stdio.h>
#include <unistd.h>

int main ()
{
  int n = 0;
  struct dirent *d;
  const char *dir_path="/home/tristan202/Nexus";
  DIR *dir = opendir(dir_path);
      while ((d = readdir(dir)) != NULL) {
        if(++n > 2)
          break;
      }
      closedir(dir);
      if (n <= 2) //Directory Empty
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * Mount = notify_notification_new ("Galaxy Nexus", "Mounted at ~/Nexus", "/home/tristan202/bin/test/android_on.png");
    system("jmtpfs ~/Nexus");
    notify_notification_show (Mount, NULL);
    }
      else
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * uMount = notify_notification_new ("Galaxy Nexus", "Unmounted", "/home/tristan202/bin/test/android_off.png");
    system("fusermount -u ~/Nexus");
    notify_notification_show (uMount, NULL);
    }
    }
4

1 回答 1

2

你有几个问题:

  1. 你不检查错误。如果opendir(2)无法打开目录并返回NULL,则继续前进,并且传入NULLtoreaddir(2)可能会导致它出现段错误。这可能是失败的,因为...
  2. 文件系统在你写的时候不理解你的意思"~",比如"~/Nexus". 它试图打开一个字面上名为"~/Nexus". 该~字符在文件系统中没有特殊含义——它对shell意味着某些东西。外壳是执行波浪扩展的外壳。为了获得您想要的文件,您需要使用正确的完整绝对路径或正确的相对路径;您可以getenv("HOME")在运行时使用它来查找自己的主目录。请注意,可以~在对system(3)函数的调用中使用,因为会system调用 shell。
  3. main()未正确声明。它必须返回int,不是void
于 2012-09-05T18:03:49.810 回答