Thursday, 6 February 2014

Writing to only specific files in a directory : C program

Suppose we have a file named 'hello' (could be even an executable one) and we need to write the content of this file into some other files of selected extension (for example, only the binary files) . This simple C program will help you to do this task. Include stdlib.h and dirent.h .

Program:

int main()
{
 DIR * d;
 FILE *fp1,*fp2;
 char* ext;
 int i;
 char * dirname = ".";
 struct dirent *handle;

 d = opendir(dirname);
 if(!d)
    printf("Directory not opened");
 while((handle=readdir(d))!=NULL)
 {
    ext=strchr(handle->d_name,'.');
    if(ext!=NULL)
       if(strcmp(ext+1,"bin")==0)
          {
            char ch;
            fp1=fopen(handle->d_name,"w");
            fp2=fopen("hello","r");
            fseek(fp2, 0, SEEK_END);
            long fsize = ftell(fp2);
            fseek(fp2, 0, SEEK_SET);

            char *string = malloc(fsize + 1);
            fread(string, fsize, 1, fp2);
            fclose(fp2);
            string[fsize] = 0;
            for(i=0;i < fsize; i++)
                fprintf(fp1,"%c",string[i]);
          }
 }
 return 0;
}



No comments:

Post a Comment