【问题标题】:File manipulations in CC中的文件操作
【发布时间】:2013-03-12 12:33:49
【问题描述】:

我正在使用一个简单的“C”代码来执行以下操作:

1) 从 .txt 文件中读取。

2) 根据 .txt 文件中存在的字符串,将创建一个目录。

我无法执行第 2 步,因为我不清楚类型转换。

这是我的代码:

#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;
}

这是错误:

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

【问题讨论】:

  • 我对感到困惑的是什么...... mkdir 接受一个字符串,而你给它一个字符。编译器也在说同样的事情......

标签: c file mkdir


【解决方案1】:

是的,编译器是对的。

您正在将字符 c 传递给 _mkdir,而不是字符串。

你应该从文件中读取字符串并将其存储到file_name(我猜你忘记了)然后

_mkdir(file_name);

见下文:

#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;
}

【讨论】:

  • 好的,我加了这个,还是不行while( ( ch = fgetc(fp) ) != EOF ) printf("%c",ch); char str[25] = ch; if( _mkdir(str) == 0 ) { printf( "Directory successfully created\n" ); }
  • @highlander141 ,为什么不使用fgets() 从文件中读取??
【解决方案2】:

这是因为你只有一个charfgetc 中的c 代表char)而_mkdir 想要一个字符串(即char *)。

您可能应该使用fgets 来读取输入。

【讨论】:

    【解决方案3】:

    如果你不想使用 fgets ,那么你可以使用它。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2016-02-21
      • 1970-01-01
      相关资源
      最近更新 更多