我正在尝试将一些数据输入到文件中,然后在控制台上阅读并打印它。
这是我的代码:
fp=fopen("user1","w+");
char line[1000];
char *c;
//write on file
while(1)
{
fgets(line,sizeof(line),stdin);
if(strcmp(line,":wq\n")==0) //input ends when user enters :wq
break;
else
fputs(line,fp);
}
//read from file
fflush(stdin);
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
else
printf("%ch",c);
}
我将数据输入为
bjsa
:WQ
输出:
h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h
有什么问题?
答案 0 :(得分:1)
我看到两个问题
1)你的fgetc
分配给一个char点。那是错的。它应该是一个int
2)写完文件后,你应该关闭它,然后打开它进行阅读
类似的东西:
fp=fopen("user1","w+");
char line[1000];
int c; // notice ......
//write on file
while(1)
{
fgets(line,sizeof(line),stdin);
if(strcmp(line,":wq\n")==0) //input ends when user enters :wq
break;
fputs(line,fp);
}
fclose(fp);
//read from file
fp=fopen("user1","r");
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
printf("%ch",c);
}
fclose(fp);