知识拓展:
文件IO操作: 对文件系统里的文件进行 打开、创建、读、写、关闭等运用。
C语言下标准文件IO接口(函数):
(1)头文件: stdio.h 输入输出函数: printf 、scanf
(2)相关函数: fopen、fread、fwrite、fclose
2.1 标准文件操作有两套函数:
1.标准C语言下的文件操作接口。fopen系列常用于: 对普通文件的读写。
2.Linux操作系统下的文件操作接口。open系列常用于: 对设备文件进行读写。 (鼠标、键盘、声卡、…)
最常用的四个函数:
#include//打开文件 FILE *fopen(const char *path, const char *mode); //读文件 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); //写文件 size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream); //关闭文件 int fclose(FILE *fp);
写函数基本操作:
#include#include #include int main() { FILE *file; int cnt; file=fopen("D:/123.txt","a+b"); if(file==NULL) { printf("文件打开失败!n"); return -1; } cnt=fwrite("1234567890",1,10,file); fclose(file); printf("cnt=%dn",cnt); return 0; }
读文件基本操作:
#include1.fileOpenWriet.c 读文件写文件#include #include int main() { FILE *file; int cnt; char buff[100]; file=fopen("D:/123.txt","rb"); //malloc if(file==NULL) { printf("文件打开失败!n"); return -1; } cnt=fread(buff,1,100,file); fclose(file); //free buff[cnt]=' '; printf("%sn",buff); printf("cnt=%dn",cnt); return 0; }
(1)程序说明:有两个磁盘文件A和B,各存放一行字母,要求把这两个文件中的信息合并并按照字典顺序进行排序,最终写入到一个新文件C中。
(2)实验代码:
a.txt
hello
b.txt
raspberry
fileOpenWrite.c
#include#include #include int main() { FILE*fa,*fb,*fc; int i,j,k; char str[100],str1[100]; char tem; strcat(str,str1);// 将str1串接到str for(i=strlen(str)-1;i>1;i--) for(j=0;j



