标准I/O库
C标准库提供了操作文件的标准I/O函数库,与系统调用相比,主要差别是实现了一个跨平台的用户态缓冲的解决方案。
一个I/O缓冲的例子如下:
1、fopen():
#include <stdio.h>
int main()
{
FILE *fp = fopen("test3","ab+");
if(fp == NULL)
{
perror("fopen");
return -1;
}
printf("打开文件成功\n");
return 0;
}
2、fread():
#include <stdio.h>
#define SIZE 1024
int main()
{
FILE *fp = fopen("BTree.c", "ab+");
if(fp == NULL)
{
perror("fopen");
return -1;
}
char buf[SIZE] = {0};
int ret = 0;
while(ret = fread(buf, sizeof(char), SIZE - 1, fp))
{
buf[ret*sizeof(char)] = '\0';
printf ("%s\n", buf);
}
if(ret == 0 && !feof(fp))
{
perror("fread");
return -1;
}
printf("文件读取结束\n");
fclose(fp);
return 0;
}
#include <stdio.h>
#define SIZE 1024
int main()
{
FILE *fp1 = fopen("1.ppt", "ab+");
if (fp1 == NULL)
{
perror ("fopen1");
return -1;
}
FILE *fp2 = fopen("2.ppt", "ab+");
if (fp2 == NULL)
{
perror ("fopen2");
return -1;
}
char buf[SIZE] = {0};
int ret = 0;
while(ret = fread(buf,sizeof(char),SIZE,fp1))
{
fwrite(buf,sizeof(char),ret,fp2);
}
if(ret == 0 && !feof(fp1))
{
perror("fread");
return -1;
}
printf("文件复制成功\n");
fclose(fp1);
fclose(fp2);
return 0;
}
4、在文件中存取结构体数据
#include <stdio.h>
#define SIZE 1024
typedef struct student
{
int id;
char name[20];
}STU;
void write_data(STU *a,int len)
{
FILE *fp = fopen("student", "ab+");
if (fp == NULL)
{
perror ("fopen");
return;
}
// 要写入个数
printf("len = %d\n",len);
fwrite(&len, sizeof(int), 1, fp);
int i;
for (i = 0; i < len; i++)
{
// 写入数据长度
int count = sizeof(a[i]);
fwrite(&count, sizeof(int), 1, fp);
// 写入数据
fwrite(&a[i], sizeof(STU), 1, fp);
}
fclose(fp);
}
void read_data()
{
FILE *fp = fopen("student", "ab+");
if (fp == NULL)
{
perror ("fopen");
return;
}
// 读记录的个数
int count;
fread (&count, sizeof(int), 1, fp);
printf ("记录个数是:%d\n", count);
int i;
STU tmp;
for (i = 0; i < count; i++)
{
int len;
fread (&len, sizeof(int), 1, fp);
// 读取数据
fread (&tmp, len, 1, fp);
printf ("id = %d, name = %s\n", tmp.id, tmp.name);
}
fclose(fp);
}
int main()
{
int i;
STU a[20];
int len = sizeof(a) / sizeof(a[0]);
for (i = 0; i < 20; i++)
{
a[i].id = i;
sprintf (a[i].name, "zhang%d", i);
}
// 写入数据
write_data(a,len);
// 读数据
//read_data();
return 0;
}