【问题标题】:How to copy characters from an array to user created file in C如何将字符从数组复制到C中用户创建的文件
【发布时间】:2018-04-17 12:01:17
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *fp;
   char file_name[50], ch, text[140];
   int i;

   printf("Enter a file name to create :");
   scanf("%s", file_name);

   fp = fopen(file_name,"w");
   if(fp == NULL)
   {
      printf("The file %s could not open !", file_name);
      exit(EXIT_FAILURE);
   }

   printf("Enter some text into %s : (enter * to finish)\n", file_name);

   while((ch=getchar()) != '*')
   {
      for(i=0;i<140;i++)
      text[i] = ch;
   }

   for(i=0;i<140;i++)
   {
      fprintf(fp,"%c",text[i]);
   }
   fclose(fp);
   printf("Your datas has been successfully copied into file %s",file_name);

   return 0;
}

它会创建文件,但不会将数组的内容复制到用户创建的文件中。所以它只是创建空文件。我在哪一部分有错误,谁能帮助解决这个问题?

【问题讨论】:

    标签: c arrays file copy


    【解决方案1】:

    见下面的代码块,这里for循环是不必要的,外部while循环就足够了。

    while((ch=getchar()) != '*')
       {
          for(i=0;i<140;i++) /* 140 times same char you are copying into text */
          text[i] = ch;
       }
    

    应该是

    int i = 0;
    while((ch=getchar()) != '*' && (i < 140)) { /* just one more condition so that it should exceeds 140 char */
               text[i] = ch;
               i++; /* when loop fail i is the count of no of char to be written to file */
       }
    

    同时使用fprintf() 将数据放入文件中

    for(index = 0;index < i ;index++) { /* i is the count */
          fprintf(fp,"%c",text[index]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2013-02-16
      • 2018-01-27
      • 2021-05-24
      • 1970-01-01
      相关资源
      最近更新 更多