1.使用fgets实现计算一个文件有几行
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 1024
int main(int argc, const char *argv[])
{
FILE *fp = fopen("zuoye.txt","r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
int count=0;
char str[MAXSIZE];
while(1)
{
if(fgets(str,MAXSIZE,fp)==NULL)
break;
count++;
}
printf("该文件有%d行\n",count);
fclose(fp);
return 0;
}
2.用fread和fwrite实现文件拷贝
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *p=fopen("zuoye2_1.txt","r");
if(NULL == p)
{
perror("fopen");
return -1;
}
FILE *p1=fopen("zuoye2_2.txt","w+");
if(NULL == p1)
{
perror("fopen");
return -1;
}
int count=0;
while(1)
{
if(fgetc(p)==EOF)
break;
count++;
}
char str[count];
fseek(p,0,SEEK_SET);
fread(str,sizeof(str),1,p);
fwrite(str,sizeof(str),1,p1);
fclose(p);
fclose(p1);
return 0;
}
缓冲区
1.只有标准IO才有缓冲区,所有的数据都先放在缓冲区中,缓冲区满或者满足一定条件后刷新缓冲区。
2.在实际生活生产过程中,我们的代码会运行在死循环中,导致缓冲区可能不满且程序没有退出。所以必须要掌握缓冲区的刷新条件。
1->全缓冲
操作对象:手动用fopen打开文件后,创建的缓冲区都是全缓冲。用FILE*类型流指针进行维护。
大小:4096bytes = 4k
//由于编译器优化,只打开不操作,此时不会真正申请缓冲区。
fputc('a', fp);
printf("%ld\n", fp->_IO_buf_end - fp->_IO_buf_base );
刷新条件:
1.缓冲区满 (要多写一个后才能刷新前4096个)
2.fflush函数,强制刷新输出流缓冲区;
#include <stdio.h>
int fflush(FILE *stream);
3.关闭流指针 fclose
4.主函数调用return
5.调用exit函数退出程序
功能:目前只要理解能退出程序即可;
原型:
#include <stdlib.h>
void exit(int status);
参数:
int status:目前随便填一个int类型整数即可,例如 1 2 0
6.输入输出转换
2->行缓冲
- 操作对象:标准输入流指针(FILE* stdin) 标准输出流指针(FILE* stdout)
- 大小:1024bytes = 1k
printf("size=%ld\n", stdout->_IO_buf_end - stdout->_IO_buf_base);
- 刷新条件:
- 缓冲区满 (要多写一个后才能刷新前1024个)
- fflush函数,强制刷新输出流缓冲区;
#include <stdio.h> int fflush(FILE *stream);
- 关闭流指针 fclose
- 主函数调用return
- 调用exit函数退出程序
功能:目前只要理解能退出程序即可; 原型: #include <stdlib.h> void exit(int status); 参数: int status:目前随便填一个int类型整数即可,例如 1 2 0
- 遇到\n字符
-
输入输出转换
3->无缓冲
- 操作对象:标准错误输出流指针(FILE* stderr) -->perror函数默认分装的就是stderr流指针。
- 大小为:1bytes,且只要往里放数据,就会直接将数据刷新出来。
- 刷新条件:无