tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 C Language > Advanced > File Operations

File Operations 

This example shows how to check whether a file exist or not and writing text strings to file.

File Name  :  
source/C/advanced/file_ops.c 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
01#include <stdio.h>
02#include <io.h>
03#include <conio.h>
04 
05int main(void)
06{
07   int status;
08   char * file_path = "C:\\file_ops.txt";
09 
10   //Check whether file exists  
11   status = access(file_path, 0);
12   if (status == 0) {
13      printf("File (%s) exists\n", file_path);
14   } else {
15      printf("File (%s) doesn't exist\n", file_path);
16   }
17 
18   //Write to file
19   FILE *fp = fopen(file_path, "w");
20   fprintf(fp, "BE THE CODER");
21 
22   //Check whether file exists
23   status = access(file_path, 0);
24   if (status == 0) {
25      printf("File (%s) exists\n", file_path);
26   } else {
27      printf("File (%s) doesn't exist\n", file_path);
28   }
29 
30   fclose(fp);
31    
32   getch();
33   return 0;
34}

It gives the following output,
File (C:\file_ops.txt) doesn't exist
File (C:\file_ops.txt) exists



 
  


  
bl  br