在屏幕上写一条信息,该如何将这条屏幕上的信息同时写入到文本里呢?带着这样的思考进行了下面的代码编写:
--------------------------------------------
#include <stdio.h>
#include <string.h>
void main(void)
{
FILE *fp; //定义文件句柄;
char Buf[30]={'0'}; //定义存放字符串的数组,并初始化;
char x[20]={'0'};//定义存放从屏幕上输入的字符串数组,并初始化;
int len;
int i,ReadNum,WirteNum,j;//ReadNum为读出的字节数;WirteNum为写入的字节数;
if ((fp=fopen("file.txt","w+t"))!=NULL)//打开文件;
{
printf("input infomation\n");
scanf("%s",x);//从屏幕上输入信息;
len=strlen(x)-1;//获取输入的字符串长度;
for(i=0,j=0;i<=len;i++,j++)//将屏幕上的信息存放到Buf中;
{
Buf[j]=x[i];
}
WirteNum=fwrite(Buf,sizeof(char),strlen(Buf),fp);//获取写入文本的字节数;Buf里的内容写入到fp中;
printf("Wirte %d items\n",WirteNum);
fclose(fp);//关闭文件句柄;
}
else
printf("Problem opening the file\n");
if ((fp=fopen("file.txt","r+t"))!=NULL)//打开文件;
{
ReadNum=fread(Buf,sizeof(char),strlen(Buf),fp);//读取Buf里面的信息,存放到fp里,并计算读出的字节数;
printf("Number of items read=%d\n",ReadNum);
printf("Contents of buffer=%s\n",Buf);//将Buf里内容输出到屏幕上。
fclose(fp);//关闭文件句柄;
}
else
printf("File could not be opened\n");
}
----------------------------------------------------------
上述的代码虽然实现了此功能,但是仔细看看还是有点不足之处,如初始化数组内存的时候直接赋值了,是不是觉得的用memset函数来初始化更好呢?
带着这样的疑问,对上面的代码稍微做了修改,如下:
----------------------------------------------------------
#include <stdio.h>
#include <string.h>
void main(void)
{
FILE *fp;
char Buf[30];//定义字符串数组;
int i,ReadNum,WirteNum,j;
/*initialize*/
memset(Buf,0,sizeof(Buf));//初始化字符串数组;
/*open file*/
if ((fp=fopen("file.txt","w+t"))!=NULL)//打开文件;
{
printf("input infomation\n");
scanf("%s",Buf);
WirteNum=fwrite(Buf,sizeof(char),strlen(Buf),fp);//将Buf里的内容写到fp里;
printf("Wirte %d items\n",WirteNum);
fclose(fp);//关闭句柄;
}
else
printf("Problem opening the file\n");
if ((fp=fopen("file.txt","r+t"))!=NULL)//打开文件;
{
ReadNum=fread(Buf,sizeof(char),strlen(Buf),fp);//从Buf里面将字符串读到fp里;
printf("Number of items read=%d\n",ReadNum);
printf("Contents of buffer=%s\n",Buf);
fclose(fp);//关闭句柄;
}
else
printf("File could not be opened\n");
}
------------------------------------------------------
到此为止该代码本应该没有什么问题了,可是今天在屏幕上输入带有空格字符的时候发现只能获取一半的内容(如下),这个原因在思考中。。。。
测试一输入:Hello world 输出:Hello
关于为何在屏幕上输入带有空格的字符串的时候只能取前半部分,原因分析如下:
--------------------
在屏幕上输入的字符串Hello world 后,字符串Hello world都会被读到输入缓冲区中,而scanf()函数取数据是遇到回车、空格、TAB就会停止,也就是为何scanf()输出结果只会取出
Hello,而world还残留在缓冲区中;所以用scanf来读取一个字符串时,字符串中是不可以出现空格的,一旦出现空格,后面的数据就会舍弃残留在缓冲区中。
用gets()函数是可以接受空格的。
将上面的程序中的【scanf("%s",Buf);】修改为【gets(Buf);】,即可解决该问题。