Saturday, July 14, 2012

Creating, Removing and Renaming Files in ANSI C

The ANSI C library stdio.h provides support for working with files and streams. To use a file, a pointer is necessary to make the connection between the physical file and the C I/O system.

1.Creating a File

To create you can use FILE* fopen(char* fileName, char* mode) using the mode "wt". This will create a new file file at the specified filename. If you are not familiar with this function, read this.

Example:
#include<stdio.h>

int main(void)
{
   const int numberOfFiles = 10;

   FILE* f = NULL;
   char filename[FILENAME_MAX];
   int i = 0;

   /*Tries to create 10 files*/
   for(i = 0; i<numberOfFiles; i++)
   {   
       /*Dynamically creates the filename*/
       sprintf(filename,"MyFile%d.fil",i);
       /*Creates the file*/
       f = fopen(filename, "wt");
       /*Checks if the file was created successfully*/
       if(f!=NULL)
       { 
           printf("%s created successfully\n",filename);
           /*Closes the current stream*/
           fclose(f);
       }
       else
       {
           printf("%s could not be created\n",filename);
       }
   }
   return 0;
}
The program above will create 10 files in the current working directory called "MyFile0fil", "MyFile1.fil", ..., "MyFile9.fil"

2.Renaming a File

To rename a file, you must the function int rename(const char *oldname, const char *newname). The function takes as parameters the name of the existing file (oldname) and the new name of the file (newname). The function will return 0 if the operation was successful and a non-zero number if it failed.

Example:
#include<stdio.h>

int main(void)
{
   int status = rename("MyFile0.fil", "MyNewFile0.lif");
   if(status == 0)
   {
      puts("New file successfully renamed");
   }
   else
   {
      puts("Rename operation failed");
   }
   return 0;
}
The program above will take the file "MyFile0.fil" created in the precedent example and it will rename it to "MyNewFile0.lif".

3.Removing a File

To remove a file, you must use the function int remove(const char *filename). The function takes as parameters a string containing the path of the file which will be removed. It returns 0 if the operation was successful or a non-zero number if an error happened along the way.

Example:
#include<stdio.h>

int main(void)
{  
   int status = remove("MyNewFile0.lif");
   if(status == 0)
   {
      puts("File successfully removed");
   }
   else
   {
      puts("Remove operation failed");
   }
   return 0;
}
The program above will remove the file "MyNewFile0.lif" created in the precedent example.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger