New API: part-to-partnum
[libguestfs.git] / daemon / devsparts.c
index c8f0256..79da41b 100644 (file)
@@ -89,6 +89,7 @@ foreach_block_device (block_dev_func_t func)
   if(0 != errno) {
     reply_with_perror ("readdir: /sys/block");
     free_stringslen(r, size);
+    closedir (dir);
     return NULL;
   }
 
@@ -175,6 +176,7 @@ add_partitions(const char *device,
   if(0 != errno) {
       reply_with_perror ("readdir: %s", devdir);
       free_stringslen(*r, *size);
+      closedir (dir);
       return -1;
   }
 
@@ -218,3 +220,28 @@ do_part_to_dev (const char *part)
 
   return r;
 }
+
+int
+do_part_to_partnum (const char *part)
+{
+  int err = 1;
+  size_t n = strlen (part);
+
+  while (n >= 1 && c_isdigit (part[n-1])) {
+    err = 0;
+    n--;
+  }
+
+  if (err) {
+    reply_with_error ("device name is not a partition");
+    return -1;
+  }
+
+  int r;
+  if (sscanf (&part[n], "%d", &r) != 1) {
+    reply_with_error ("could not parse number");
+    return -1;
+  }
+
+  return r;
+}