Search code examples
cfilemkdir

File manipulations in C


I am using a simple 'C' code to do the following:

1) Read from a .txt file.

2) Based on the string present in the .txt file, a directory will be created.

I am not able to perform step-2, as I am not clear with type conversions.

Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <direct.h>

int main()
{
   char ch, file_name[25];
   FILE *fp;

   //printf("Enter the name of file you wish to see\n");
   //gets(file_name);

   fp = fopen("input.txt","r"); // read mode

   if( fp == NULL )
    {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
    }

   printf("The contents of %s file are :\n", file_name);

   while( ( ch = fgetc(fp) ) != EOF )
      printf("%c",ch);

    if( _mkdir(ch ) == 0 )
   {
      printf( "Directory successfully created\n" );
      printf("\n");
   }
   fclose(fp);
   return 0;
}

Here is the error:

 *error #2140: Type error in argument 1 to '_mkdir'; expected 'const char *' but found 'char'.*

Solution

  • YES, compiler is right.

    You are passing a char c to _mkdir, instead of a string.

    You should read the string from file and store it to file_name (I guess you forget) and then

    _mkdir(file_name);
    

    See below:

    #include <stdio.h>
    #include <stdlib.h>
    #include <direct.h>
    
    
    int main()
    {
        char file_name[25];
        FILE *fp;
    
        fp = fopen("input.txt", "r"); // read mode
    
        if (fp == NULL)
        {
            perror("Error while opening the file.\n");
            exit(EXIT_FAILURE);
        }
    
        fgets(file_name, 25, fp);
    
        _mkdir(file_name);
    
        fclose(fp);
        return 0;
    }