首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

c语言关于文件的操作,该如何解决

2012-04-06 
c语言关于文件的操作用C的fputc()函数,像这样,为什么不能将输入的字符输入到文件呢?求解。。。。。。。。谢谢,呵呵

c语言关于文件的操作
用C的fputc()函数,像这样,为什么不能将输入的字符输入到文件呢?求解。。。。。。。。
谢谢,呵呵

代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp = NULL;
  fp = fopen("testfile.txt","r|w");
  if(fp==NULL)
  {
printf("can not open the file!\n");
exit(0);
  }
  else
  {
printf("hah,have opened the file!\n");
  }
  char ch;
  while(ch!='q')
  {
ch = getchar();
fputc(ch,fp);
  }
  fclose(fp);
  return 0;
}

[解决办法]
[code=C/C#include] <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = NULL;
fp = fopen("testfile.txt","r|w");//包括read方式时,必须保证工程目录下有testfile.txt
if(fp==NULL)
{
printf("can not open the file!\n");
exit(0);
}
else
{
printf("hah,have opened the file!\n");
}
char ch;
ch = getchar();//加这一句,初始化ch
while(ch!='q')
{
fputc(ch,fp);
ch = getchar();
}
fclose(fp);
return 0;
}code
[解决办法]

C/C++ code
#include <stdio.h>#include <stdlib.h>int main(){  FILE *fp = NULL;  fp = fopen("testfile.txt","r | w");  if(fp==NULL)  {printf("can not open the file!\n");exit(0);  }  else  {printf("hah,have opened the file!\n");  }  char ch;  while(ch = getchar())  {    if (ch=='q')    break;    fputc(ch,fp);  }  fclose(fp);  return 0;}
[解决办法]
上面的贴错了
C/C++ code
#include <stdio.h>#include <stdlib.h>int main(){  FILE *fp = NULL;  fp = fopen("testfile.txt","w");  if(fp==NULL)  {printf("can not open the file!\n");exit(0);  }  else  {printf("hah,have opened the file!\n");  }  char ch;  while(ch = getchar())  {    if (ch=='q')    break;    fputc(ch,fp);  }  fclose(fp);  return 0;} 

热点排行