Coupon Accepted Successfully!


Question 1

How do stat(), fstat(), vstat() work? How to check whether a file exists?

The functions stat(), fstat(), lstat() are used to get the file status.

Here are their prototypes


int stat(const char *file_name, struct stat *buf);
int fstat(int file_desc, struct stat *buf);
int lstat(const char *file_name, struct stat *buf);

These functions return information about the specified file. You do not need any access rights to the file to get this information but you need search rights to all directories named in the path leading to the file.

stat      -     stats the file pointed to by file_name and fills in buf.
lstat     -     identical to stat, except in the case of a symbolic link, 
                where the link itself is stat-ed, not the file that it refers to.
fstat     -     identical to stat, only the open file pointed to by file_desc 
                is stated in place of file_name.

They all return a stat structure, which contains the following fields:

              struct stat {
                  dev_t         st_dev;      /* device */
                  ino_t         st_ino;      /* inode */
                  mode_t        st_mode;     /* protection */
                  nlink_t       st_nlink;    /* number of hard links */
                  uid_t         st_uid;      /* user ID of owner */
                  gid_t         st_gid;      /* group ID of owner */
                  dev_t         st_rdev;     /* device type (if inode device) */
                  off_t         st_size;     /* total size, in bytes */
                  unsigned long st_blksize;  /* blocksize for filesystem I/O */
                  unsigned long st_blocks;   /* number of blocks allocated */
                  time_t        st_atime;    /* time of last access */
                  time_t        st_mtime;    /* time of last modification */
                  time_t        st_ctime;    /* time of last change */

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

Here is a small piece of code which returns the size of a file by accessing the st_size member of the stat structure.

boolean get_file_size(char *file_path,
                      int  *file_size)
  struct stat stat_buffer;

  if (stat((char *)file_path, &stat_buffer)!=0)

  *file_size =  stat_buffer.st_size;

So how do we check if a file exists or not?

Use functions like stat() as used above to find out if a file exits or not. Also, one can use fopen(). When using fopen(), just open for reading and close immediately. If the file does not exists, fopen() will given an error.

Question 2

How can I insert or delete a line (or record) in the middle of a file?

The only way is to rewrite the file.

Question 3

How can I recover the file name using its file descriptor?

Have a wrapper around fopen() to remember the names of files as you open them.

Question 4

How can I delete a file? How do I copy files? How can I read a directory in a C program?

Deleting a file

The Standard C Library function is remove(). If thats not there, use unlink().

Copying a file

Directly use system() to invoke the operating system's copy() utility, or open the source and destination files, read characters or blocks of characters from the source file, and write them to the destination file.

How to read directories?

Use the opendir() and readdir() functions, which are part of the POSIX standard and are available on most Unix variants.

Question 5

Whats the use of fopen(), fclose(), fprintf(), getc(), putc(), getw(), putw(), fscanf(), feof(), ftell(), fseek(), rewind(), fread(), fwrite(), fgets(), fputs(), freopen(), fflush(), ungetc()?

Whew!, thats a huge list.


This function is used to open a stream.

FILE *fp;
fp = fopen("filename","mode");
fp = fopen("data","r");
fp = fopen("results","w");


    "r"     -> Open for reading.
    "w"     -> Open for writing.
    "a"     -> Open for appending.
    "r+"    -> Both reading and writing.
    "w+"    -> Both reading and writing, create new file if it exists,
    "a+"    -> Open for both reading and appending.


fclose() is used to close a stream .


putc(), getc(), putw(), getw(), fgetc(), getchar(), putchar(), fputs()

These functions are used to read/write different types of data to the stream.

putw(integer, fp);

fprintf(), fscanf()

Read/Write formatted data from/to the stream.

fprintf(fp,"control string",list);
fscanf(fp,"control string", list);


Check the status of a stream


ftell(), fseek(), rewind(), fgetpos(), fsetpos()

Reposition the file pointer of a stream

n=ftell(fp); //Relative offset (in bytes) of the current position.

fseek(fp, offset, position); 

Position can be 

0->start of file
1->current position
2->end of file

fseek(fp,0L,0);  // Same as rewind.
fseek(fp,0L,1);  // Stay at current position.
fseek(fp,0L,2);  // Past end of file.
fseek(fp,m,0);   // Move to (m+1) byte.
fseek(fp,m,1)    // Go forward m bytes.
fseek(fp,-m,1);  // Go backward m bytes from current position.
fseek(fp,-m,2);  // Go backward from end of file.

fread(), fwrite()

Binary stream input/output.

fwrite(&customer, sizeof(record),1,fp);

Here is a simple piece of code which reads from a file


int main()

 FILE *f;
 char buffer[1000];
  printf("\nOpenened the file!\n");
   printf("(%d)-> %s\n",strlen(buffer),buffer);

Question 6

How to check if a file is a binary file or an ascii file?

Here is some sample C code. The idea is to check the bytes in the file to see if they are ASCII or not...


int main(int argc, char *argv[])
 unsigned char ch;
 FILE *file;
 int binaryFile = FALSE;

 file = fopen(, "rb");            // Open in Binary mode for the first time.

 while((fread(&ch, 1, 1, file) == 1) && (binaryFile == FALSE))
    if(ch  13 && ch      {
       binaryFile = 1;                  


    file = fopen(, "rb");   
    file = fopen(, "r");

    while(fread(&ch, 1, 1, file) == 1)  
      // Do whatever you want here with the binary file byte...
    while(fread(&ch, 1, 1, file) == 1) 
      // This is ASCII data, can easily print it!



Test Your Skills Now!
Take a Quiz now
Reviewer Name