简单的C app给出了分段错误

时间:2012-09-05 17:50:09

标签: c segmentation-fault

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);
    }
    }

1 个答案:

答案 0 :(得分:2)

你有几个问题:

  1. 您不会检查错误。如果opendir(2)无法打开目录并返回NULL,那么您继续前进,将NULL传递给readdir(2)可能会导致段错误。这可能是失败的原因......
  2. "~"中写文件时,文件系统无法理解您的意思,如"~/Nexus"中所示。它尝试打开名为"~/Nexus"字面文件。 ~字符在文件系统中没有特殊含义 - 它对 shell 意味着什么。 shell是执行tilde expansion的shell。为了获得所需的文件,您需要使用正确的完整绝对路径或正确的相对路径;您可以使用getenv("HOME")在运行时查找自己的主目录。请注意,在~函数的调用中可以使用system(3),因为system会调用shell。
  3. main()未正确声明。它必须返回int,而不是void