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

一个追加有关问题

2012-06-19 
一个追加问题//addaword.c 使用fprintf(),fscanf(),和rewind()函数#include stdio.h#include stdlib.h

一个追加问题
//addaword.c 使用fprintf(),fscanf(),和rewind()函数
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main(void)
{
  FILE * fp;
char words[MAX];

if((fp = fopen("words","a+")) == NULL)
{
fprintf(stdout,"Can't open \"words\" file.\n");
exit(1);
}
puts("Enter words to add to the file; press the Enter");
puts("key at the beginning of a line to terminate.");
while(gets(words) != NULL && words[0] != '\0')
fprintf(fp,"%s",words);
puts("File contents: ");
rewind(fp); //回到文件的开始处
while(fscanf(fp,"%s",words) == 1)
puts(words);
if(fclose(fp) != 0)
fprintf(stderr,"Errou closing file\n");
return 0;
}

-------------------------
输入 
aaa bbb ccc
输出
aaa
bbb
ccc
------
第二次追回输入
111 222
333
输出
aaa
bbb
ccc111
222333
-------------------
疑问:我认为应该追回之后,应该输出
aaa
bbb
ccc
111
222333
puts()不是应该自动追加一个回车换行么?

[解决办法]
造成这个现象的原因是gets
char * gets ( char * str ); <cstdio> 

Get string from stdin

Reads characters from stdin and stores them as a string into str until a newline character ('\n') or the End-of-File is reached.
The ending newline character ('\n') is not included in the string.

虽然你是以回车方式分开输入的,但是实际是回车符根本没有写到文件里面去
文件里面的内容是 aaa bbb ccc111 222333
ccc与111之间的那个回车并没有读到文件里面去,实际写的时候会连到一起。

函数名: fscanf 功 能: 从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束

fscanf是碰到空格或回车才会认为一次读取结束 ccc111直接被读到一个字符串中了

热点排行