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に渡すとセグメンテーション違反が発生する可能性があります。これはおそらく失敗しています...NULLreaddir(2)
  2. "~"ファイル システムは、 のように を書き込んだときの意味を理解していません"~/Nexus"文字通り名前が付けられたファイルを開こうとします"~/Nexus"。この~文字は、ファイル システムでは特別な意味を持ちません。シェルにとっては意味があります。シェルは、チルダ展開を実行するシェルです。必要なファイルを取得するには、正しい絶対パスまたは正しい相対パスを使用する必要があります。getenv("HOME")実行時に独自のホーム ディレクトリを見つけるために使用できます。シェルを呼び出すため、関数~の呼び出しで使用しても問題ないことに注意してください。system(3)system
  3. main()正しく宣言されていません。ではなく、返さなければなりませintvoid
于 2012-09-05T18:03:49.810 に答える