注册 登录
编程论坛 C++教室

帮忙! 自己写的计数函数出错!

Hellish 发布于 2007-03-15 22:49, 609 次点击
#include<stdio.h>
#include<iostream.h>
void main()
{ int c=0;
FILE *fp;
if((fp=fopen("c:\\count.txt","wt+"))==NULL)
{
cout<<"can not open file"<<endl;
getchar();
}
c=fgetc(fp);
c++;
fputc(c,fp);
cout<<c<<endl;
fclose(fp);
}
能通过编译,但是文件不能写入, 达人帮忙啊!
4 回复
#2
Hellish2007-03-15 23:14
那位能帮帮忙啊,
#3
cfnxy2007-03-17 09:13

楼主什么意思啊?是想从一个文件中读出字符再写入原文件吗?本来那个文件就是空的,您什么也没读出来,当然什么也不会写入了。而且要有一个循环语句才能不停的读和写啊。
#include<stdio.h>
#include<iostream.h>
void main()
{ int c=0;char cc;
FILE *fp;
if((fp=fopen("c:\\count.txt","wt+"))==NULL)
{
cout<<"can not open file"<<endl;
getchar();
}
c=fgetc(fp);
c++;
while ((cc=getchar())!='\n')
fputc(cc,fp);
cout<<c<<endl;
fclose(fp);
}

#4
litcatyx2007-03-17 09:44
int main()
{
const int MAXLEN=100;
const char filename[]="f:\\count.txt";

int count=0;
char buf[MAXLEN]={'0','\0'};

FILE *fp=0;
if(fp=fopen(filename,"r"))
{
char c;
while((c=fgetc(fp))!=EOF)
count=count*10+c-'0';
++count;
itoa(count,buf,10);
fclose(fp);
}
if(fp=fopen(filename,"w"))
{
char *p=buf;
while(*p!='\0')
fputc(*p++,fp);
fclose(fp);
}
else
{
cout<<"Can't not open file!"<<endl;
}
return 0;
}
#5
Hellish2007-04-01 08:48
以下是引用cfnxy在2007-3-17 9:13:06的发言:

楼主什么意思啊?是想从一个文件中读出字符再写入原文件吗?本来那个文件就是空的,您什么也没读出来,当然什么也不会写入了。而且要有一个循环语句才能不停的读和写啊。
#include<stdio.h>
#include<iostream.h>
void main()
{ int c=0;char cc;
FILE *fp;
if((fp=fopen("c:\\count.txt","wt+"))==NULL)
{
cout<<"can not open file"<<endl;
getchar();
}
c=fgetc(fp);
c++;
while ((cc=getchar())!='\n')
fputc(cc,fp);
cout<<c<<endl;
fclose(fp);
}

我的意思是生成执行文件后, 点击一次(调用一次), 文件里面的数就自动加一, 而不是将输入的数保存在文件中

1