读书人

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

发布时间: 2012-04-06 12:22:24 作者: rapoo

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

读书人网 >C语言

热点推荐