c - 如何将字符从数组复制到用户在 C 中创建的文件

标签 c arrays file copy

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

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

最佳答案

参见下面的代码块,这里的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]);
}

关于c - 如何将字符从数组复制到用户在 C 中创建的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49877555/

相关文章:

c - 将宏的输入存储在数组中 (C)

c - 在windows中发送Raw arp回复包

c - 在 C 中取出一段字符数组的问题

c - 如何在C中检查文件是否存在并创建新文件

c - 如何使用 printf() 以十六进制形式一一读取内存字节(因此没有任何格式)

c - 如何在结构中包含结构数组?

arrays - Fortran 中的数组第一个索引

javascript - 如何根据起始字母过滤数组

xcode - 为什么我不能从我的 XCode 项目中删除文件?

python - 如何使用 Python Regex 查找首字母大写的所有单词