Hello. I have this simple program that open a file and read lines from it and print them to screen.

#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

int main() {
    char line[4096];
    FILE *fp = fopen("/root/Desktop/testfile","r");
    if( fp == NULL ) {
        exit(1);
    }

    while(fgets( line, sizeof(line), fp ) != NULL ) {
        printf("%s",line);
    }

    if( fp != NULL ) {
        fclose(fp);
    }
    return 0;
}

There is nothing wrong withthe program. It works very well, but i have descovered that if i follow the next scenario :

  1. i start the program
  2. while the program is running i delete "/root/Desktop/testfile"

the program continue showing lines from file even the file don't exist anymore.
My problem is that i don't understand why it still prints lines after file deletion.

I run the program on CentOS 5. ( don't know if this is usefull).

Thanks in advance for any suggestion.

the program continue showing lines from file even the file don't exist anymore.
My problem is that i don't understand why it still prints lines after file deletion.

I do not know how CentOS manages files in use, but it looks like the file is loaded into either memory or a temporary file to protect against exactly what you are trying to do. :) M$ Windows protects files in use by throwing up an error dialog box and not deleting the file.

When a file is created in linux, a inode number is assigned to it and name of a file is link to that inode number. using this link we can perform any operations on the chosen file.
Now when you open a file, kernel increments the reference count of that file in its file table entry .
So even if you delete the file in between, the contents are still accessible to the process which has opened it because it is still pointing to same inode number. After completion of file operation when you will use fclose() kernel will decrement the reference count and hence file will be no longer accessible. When only reference count is zero, kernel frees the block that has contents of a file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.