当前位置: 代码迷 >> 综合 >> C语言字符串与文件读写函数 fgets(),fputs()......
  详细解决方案

C语言字符串与文件读写函数 fgets(),fputs()......

热度:71   发布时间:2024-01-19 15:43:47.0

 

《C语言入门经典 第四版 霍顿》 P470

 

 

// 从文本文件中读出一个字符串
#include <stdio.h>
#include <stdlib.h> 
// #include <stdbool.h>  // 编译器报错,没有这个文件 据说是bool 类型变量定义的头文件
const int LENGTH = 80;
int main(void)
{
char *proverbs[]=
{
"Many a mickle makes a muckle.\n",
"Too many cooks spoil the broth.\n",
"He who laughs last didn't get the joke in the first place.\n"
};
char more[LENGTH];
FILE *pfile = NULL;
char *filename = "c:\\myfile.txt";
//	if(!(pfile = fopen(filename,"w"))) //  因为没有stdbool.h头文件,所以要这句拆开写
pfile = fopen(filename,"w");
if(pfile==NULL)
{
printf("Error opening %s for writing. Program terminated.",filename);
exit(1);
}
int count = sizeof proverbs/sizeof proverbs[0];  // 难道proverbs每个元素都等长?显然不是,难道他们的分配的空间做了对齐处理了?
for(int i=0;i<count;i++)
fputs(proverbs[i],pfile);   // 从pfile 指向的文件重读取字符串 到 proverbs
fclose(pfile);
//		if(!(pfile = fopen(filename,"a"))) // 以追加的方式打开
pfile = fopen(filename,"a");
if(pfile==NULL)
{
printf("Error opening %s for writing. Program terminated.",filename);
exit(1);
}
printf("Enter proverbs of less than 80 characters or press Enter to end:\n");
while(true)
{
fgets(more,LENGTH,stdin); //读取一条谚语从 键盘 到 more
if(more[0]=='\n')break;  // 如果是空行,则结束读取操作。
fputs(more,pfile); // 输出more 到 pfile
}
fclose(pfile);
//	if(!(pfile = fopen(filename,"r"))) // 以只读的方式打开文件
pfile = fopen(filename,"r");
if(pfile==NULL)
{
printf("Error opening %s for reading. Program terminated.",filename);
exit(1);
}
printf("The proverbs in the file are :\n\n");
while(fgets(more,LENGTH,pfile))// 读取一条谚语:从pfile 到 more,(没有遇到EOF ?) 
printf("%s",more);
fclose(pfile);
//	remove(filename);
char readstring[LENGTH];
pfile = fopen(filename,"r");
fgets(readstring,LENGTH,pfile);		// 读取文件的第一行
printf("%s",readstring);
fgets(readstring,LENGTH,pfile);	// 读取文件的第二行	
printf("%s",readstring);
fgets(readstring,LENGTH,pfile);	// 读取文件的第三行	
printf("%s",readstring);
fgets(readstring,LENGTH,pfile);		// 读取文件的第四行	,文件只有四行,读完了
printf("%s",readstring);
fgets(readstring,LENGTH,pfile);	// 读取文件的第五行	,没有第五行了,测试表明还是读取的第四行
printf("%s",readstring);
fgets(readstring,LENGTH,pfile);	// 读取文件的第六行	,没有第六行了,测试表明还是读取的第四行
printf("%s",readstring);
fclose(pfile);  // 关闭文件指针
//---
return 0;
}

 

输出结果:

 

Enter proverbs of less than 80 characters or press Enter to end:
The proverbs in the file are :

Many a mickle makes a muckle.
Too many cooks spoil the broth.
He who laughs last didn't get the joke in the first place.
test test test
Many a mickle makes a muckle.
Too many cooks spoil the broth.
He who laughs last didn't get the joke in the first place.
test test test
test test test
test test test

 

 

 


 1) fgets(readstring,LENGTH,pfile); 每执行一次,刚好读取一行,问题是被读取的文件在被关闭之前,是怎么知道移到下一行的?

         难道是文件指针移动了?

2) 文件读了4行,已经读完了,再次执行fgets(readstring,LENGTH,pfile);都是输出文件的最后一行,可能文件指针在被关闭前,

        指针总之指在每行的开始?