c - Return value of fprintf -


#include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h> int main(void) {     file *fh = fopen ("file.txt", "w");     if (fh != null) {         int = 0;         while(i < 5){             if (fprintf (fh, "%s", "hello") < 0)             {                 fprintf (stderr, "err=%d: %s\n", errno, strerror (errno));             }             if(ferror(fh))             {                 printf("wrong\n");             }             sleep(10);         }     }       return(0); } 

when delete file "file.txt" during time program running, expect fprintf return value lesser 0 print error message. times fprintf returns the size of "hello" string 5.

note: since there sleep call 10 seconds, deleted file before program terminates.

clarify me on how produce error message if fprintf/fwrite writes file no longer exists (pointed file-descriptor).

on unix-like systems, "deleting" file not physically delete file on disk. merely decreases link count 1. file not deleted until last link goes away. why system call that's invoked rm command called unlink. man 2 unlink more information.

one consequence of can seen if create hard link file:

echo "hello" > file0 ln file0 file1 rm file0 

the rm file0 command means file no longer visible name, it's still visible via other name file1. if rm file1, actual file vanish.

another way prevent file being removed process have open. program creates file, , creates directory entry name "file.txt". when type rm file.txt outside program, remove directory entry, not file. program can still write file. can seek beginning of file , read again.

if program calls fclose(fh), or if terminates (which implicitly closes open files), last reference disk file vanish, , actual file on disk removed.

non-unix systems (like windows) behave differently.


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -