Как узнать свободное место на диске?

Материал из DRKB


В коде используется функция ExecCmdine из статьи: Как запустить консольное приложение и перехватить вывод?

function GetFreeSpace(Share: string): Integer; { in Kb }
var
  t: TStringList;
  i: Integer;
  temp: string;
  mesure: Char;
  multi: Integer;
  f: Real;

  function GetBefore(subStr, str: string): string;
  begin
    if Pos(subStr, str) > 0 then
      Result := Copy(str, 1, Pos(subStr, str)-1)
    else
      Result := '';
  end;

  function GetAfter(subStr, str: string): string;
  begin
    if Pos(subStr, str) > 0 then
      Result := Copy(str, Pos(subStr, str) + Length(subStr), Length(str))
    else
      Result := '';
  end;

begin
  Result := -1;
  t := TStringList.Create;
  try
    ExecCmdine('df -h', t);
    for i:=0 to t.Count-1 do
    begin
      if Pos(Share, t[i]) = 1 then
      begin
        temp := Trim(GetAfter(Share, t[i]));
        temp := Trim(GetAfter(' ', temp));
        temp := Trim(GetAfter(' ', temp));
        temp := Trim(GetBefore(' ', temp));
        if temp = '' then exit;
        mesure := temp[Length(temp)];
        case mesure of
          'G', 'g': multi := 1024*1024;
          'M', 'm': multi := 1024;
          'K', 'k': multi := 1;
        else
          multi := 0;
        end;
        try
          f := StrToFloat(Copy(temp, 1, Length(temp)-1));
        except
          f := 0;
        end;
        Result := Round(f * multi);
      end;
    end;
  finally
    t.Free();
  end;
end;


Использование:

GetFreeSpace('/dev/hda5')

Примечание - под отладчиком Kylix код может не работать. Надо запускать приложение не под Kylix для того чтобы удостовериться что код работает.

Более подробную информацию можно получить запустив в консоли:

man df


Author: Vit
ID: 04629