Recover a deleted file using undelete() in C

2.2k views Asked by At

I'm just trying to recover a file in C on an HFS+ formatted Volumn. According to

man undelete

NAME undelete -- attempt to recover a deleted file

LIBRARY Standard C Library (libc, -lc)

SYNOPSIS #include

 int
 undelete(const char *path);

DESCRIPTION

The undelete() system call attempts to recover the deleted file named by path. Currently, this works only when the named object is a whiteout in a union file system. The system call removes the whiteout causing any objects in a lower layer of the union stack to become visible once more.

Eventually, the undelete() functionality may be expanded to other file systems able to recover deleted files such as the log-structured file system.

RETURN VALUES

The undelete() function returns the value 0 if successful; otherwise the value -1 is returned and the global variable errno is set to indicate the error.

so the Program is simple:

The current directory (pwd) is /Users/Leo/Desktop/ and I'm on a Mac 10.7.2 with HFS+ Filesystem.

#include <unistd.h>
int main()
{
    char a="/Users/Leo/Desktop/test/a.out";//I delete a.out using rm for testing
    const char* pa=&a;
    return undelete(pa);
}

But when I run the program, I got shell returned 255.

Any idea? Thanks

2

There are 2 answers

2
William Pursell On BEST ANSWER

undelete is failing. To find out why, check errno. For example:

#include <unistd.h>
int main( int argc, char **argv )
{
    char *path = argc > 1 ? argv[ 1 ] : "a.out";

    if( undelete(path))
        perror( path );
    return 0;
}

Although it appears your problem is that you have a char instead of a char pointer. You should have gotten a compiler warning.

2
DarkDust On

First, you need to check the return value and evaluate it. If it is -1 then print an error message, for example with perror or by formatting an error message and using strerror(errno).

But you've also got a major bug before you even attempt to call undelete:

char a="/Users/Leo/Desktop/test/a.out";
const char* pa=&a;

This will first assign a value (the pointer to your string) to a char, a single byte value. The compiler even warns about that with warning: initialization makes integer from pointer without a cast. In my case, a then had the value D/0x44, but it could have been anything. You then store the pointer to that single byte in pa. What you want instead is:

const char* pa="/Users/Leo/Desktop/test/a.out";