#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/