浅拷贝和深拷贝
指针变量作为 结构体的成员
浅拷贝:两个结构体变量 中的 指针成员 指向 同一块堆区空间。
深拷贝:两个结构体变量 中的 指针成员 指向 各自的堆区空间。
文件
1、文件的存取过程
缓冲区的目的:提高存取效率 磁盘使用寿命。
2、磁盘文件的分类
物理上: 所有的磁盘文件都是 二进制存储,以字节为单位 顺序存储。
逻辑上的文件分类:
文本文件:基于字符编码的文件
二进制文件:基于值编码的文件
fopen打开一个文件
FILE *fp=NULL;
fp=open(文件名,文件使用方式);
文件使用方式:
r:以只读的方式打开文件
w:以只写的方式打开文件
a:以追加的方式打开文件(往文件的末尾写入数据)
+:以可读可写的方式打开
b:以二进制的方式打开文件
t:以文本的方式打开文件(省略)
关闭文件fclose
fclose(文件指针);
文件的字节读写
1、字节的读操作 fgetc函数
ch=fgetc(fp);
2、字节的写操作 fputc
fputc(ch,fp);
文件的字符串读写
1、使用fputs 往文件中写入一个字符串
#include<stdio.h>
int main(int argc, char *argv[])
{
char *buf[] = { " 静夜思 \n","窗前明月光\n","疑似地上霜\n","举头望明月\n","低头思故乡" };
int n = sizeof(buf) / sizeof(buf[0]);
FILE *fp = NULL;
fp = fopen("c.txt", "w");
if (fp == NULL)
{
perror("fopen");
return;
}
int i = 0;
for (i = 0; i < n; i++)
{
fputs(buf[i], fp);
}
fclose(fp);
return 0;
}
运行结果:
2、使用fgets从文件中获取字符串
#include<stdio.h>
int main(int argc, char *argv[])
{
char buf[128] = "";
FILE *fp=NULL;
fp = fopen("c.txt", "r");
if (fp == NULL)
{
perror("fopen");
return;
}
while (fgets(buf, sizeof(buf), fp))
printf("%s\n", buf);
fclose(fp);
return 0;
}
运行结果
文件的块读写
1、使用fwrite 将 数据块 写入到文件中
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct
{
char name[16];
int num;
float score;
}STU;
int main(int argc, char *argv[])
{
STU stu[] = {
{"aaa",101,98.30},
{"bbb",102,78.65},
{"ccc",103,23.33}
};
int n = sizeof(stu) / sizeof(stu[0]);
FILE *fp = NULL;
fp = fopen("stu.txt", "w");
if (fp == NULL)
{
perror("fopen");
return;
}
fwrite(stu, sizeof(STU), n, fp);
fclose(fp);
return 0;
}
运行结果:
2、使用fread 从文件中 读取 数据块
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct
{
char name[16];
int num;
float score;
}STU;
int main(int argc, char *argv[])
{
STU stu[3];
FILE *fp = NULL;
fp = fopen("stu.txt", "r");
if (fp == NULL)
{
perror("fopen");
return;
}
fread(stu, sizeof(STU), 3, fp);
int i = 0;
for (i = 0; i < 3; i++)
printf("name=%s,num=%d,score=%f\n", \
stu[i].name, stu[i].num, stu[i].score);
fclose(fp);
return 0;
}
运行结果: