deleting a file name by its handle

All,

I am having three function 

1.open
2.process
3.close.

Open will open a file and process will process a file and close will close the file ..

I can able to close the file by its filehandler.Is there is anyway that i can get the file name by filehandle and remove it after closing the file .Please help ....

Thanks,
Arun.

See 'man 2 stat'.

there is no simple way to get a filename from a file descriptor (handle).

If the file in question is a temporary file look into man tmpfile - the file is automatically deleted on close.

Otherwise, it is easier to have the shell script that passed the filename (to the C process) delete the file.

As last suggestion - pass the filename around as an argument


char global_filename[128]={0x0};

int openit(char *filename)
{
    int filedesc=open(filename, O_RDONLY);
    if(filesdesc < 0) { 
        perror("error opening file");
        exit(EXIT_FAILURE);
    }
    return filedesc;
}

void process(int fd)
{

}

void closeit(int fd)
{
     if(close(fd) <0) {

        perror("error closing file");
        exit(EXIT_FAILURE);
     }     
}

void deleteit(char *filename)
{
     remove(filename);
}

int main(int argc, char *argv[])
{
     int fd=openit(argv[1]);
     process(fd);
     closeit(fd);
     deleteit(argv[1]);
     return 0;
}

You can open the file and immediately remove it. Then simply use the file...because it is open by a process, the OS will not actually remove it until the final close. When you are finished with it, a simple close() will remove it from existence. And an exit() is good enough too, all opened files are closed on exit.

Thanks all for your answer .

As i saw jim told in delete function it takes argument as filename. But i want to know whether it is possible to get the filehandle as argument and then by using it get the file name and delete the file. Since in design i am having the control of filehandle only . Please let me know.

Thanks Again,
Arun Kumar.

I don't think you'll be able to get the file name. As suggested above, you can get information about the file (with the fstat() function call), but that doesn't help you because it won't give you a name.

What it will give you, however, is the device and id information about where the file is stored. My guess is that this information should be sufficient to unlink the file from the file system, however, if you *really* need to do this you'll have to start looking for the source code to "unlink" for your system. Then you'll need to piece together an unlink that can take the data from a file handle rather than a file name, and this will certainly be non-portable.

Regardless, methinks this is a tough nut to crack without having the file name available to you when you want to delete it.